一.原始Dao方式

1.引入jar包(maven文件和下面的Mapper代理方式一样)

2.applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 
<!-- 加载配置文件 -->
<context:property-placeholder location="config/jdbc.properties"/>
 
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${jdbcUrl}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>         
<!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource"ref="dataSource" />
 
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="config/mybatis/sqlSessionConfig.xml" />
</bean>
 
<!-- 配置dao -->
<bean id="userDao" class="gwd.ssm.dao.UserDaoImp">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>


3.sqlSessionConfig.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="gwd/ssm/po/user.xml"/>
</mappers>
</configuration>


4.User.xml(和User.java放一起)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="gwd.ssm.po.User">
select * from users where id=#{value}
</select>
</mapper>


5.UserDao.java:

package gwd.ssm.dao;
import gwd.ssm.po.User;
public interface UserDao {
public User findUserById(int id);
}
 

UserDaoImp.java:

package gwd.ssm.dao;
import gwd.ssm.po.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
 
public class UserDaoImp extends SqlSessionDaoSupport implements UserDao {
 
public User findUserById(int id) {
// TODO Auto-generated method stub
SqlSession sqlSession=this.getSqlSession();//sqlSessionFactory方法中有set方法
User user=sqlSession.selectOne("test.findUserById",id);
return user;
}
}

6.Test

public class UserMapperTest {

private ApplicationContext applicationContext;

@Before

public void setUp(){

applicationContext=new  FileSystemXmlApplicationContext("config/spring/applicationContext.xml");

}

@Test

public void testFindUserById() {

UserMapper userMapper=(UserMapper)applicationContext.getBean("userMapper");//userMapper和UserMapper对应

User user=userMapper.findUserById(2);

System.out.println(user);

}

}


二:Mapper代理方式

1.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>PetTest</groupId>
  <artifactId>pet-commonTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>pet-commonTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <spring.version>4.2.0.RELEASE</spring.version>
      <jackson-core.version>2.6.1</jackson-core.version>
      <!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.7</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!-- servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
   
    <!-- mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
    </dependency>

    <!-- JSTL标签类 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<!-- 格式化对象,方便输出日志 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.3</version>
    </dependency>
    
	  <dependency>
	    <groupId>commons-dbcp</groupId>
	    <artifactId>commons-dbcp</artifactId>
	    <version>1.4</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>pethome</finalName>
    <resources>  
      <!-- maven项目中src源代码下的xml等资源文件编译进classes文件夹,
      	注意:如果没有这个,它会自动搜索resources下是否有mapper.xml文件,
      	如果没有就会报org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.pet.mapper.PetMapper.selectByPrimaryKey-->
      <resource>  
        <directory>src/main/java</directory>  
        <includes>  
          <include>**/*.xml</include>  
        </includes>  
      </resource>
      
      <!--将resources目录下的配置文件编译进classes文件  -->  
      <resource>
			<directory>src/main/resources</directory>
	  </resource>
    </resources>  
  </build> 
</project>

2.引入配置文件

(1)PetMapper.java

package com.pet.mapper;

import java.util.List;
import com.pet.bean.Pet;
public interface PetMapper {
    public Pet selectByPrimaryKey(Integer id);
    public List<Pet> getAll();
}

(2)PetMapper.xml(自动生成)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pet.mapper.PetMapper" >
  <resultMap id="BaseResultMap" type="com.pet.bean.Pet" >
    <id column="ID" property="id" jdbcType="INTEGER" />
    <result column="PETNAME" property="petname" jdbcType="VARCHAR" />
    <result column="AGE" property="age" jdbcType="INTEGER" />
    <result column="STATUS" property="status" jdbcType="VARCHAR" />
    <result column="MED_HISTORY" property="medHistory" jdbcType="VARCHAR" />
    <result column="FEATHERS" property="feathers" jdbcType="VARCHAR" />
    <result column="VACCINATION" property="vaccination" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    ID, PETNAME, AGE, STATUS, MED_HISTORY, FEATHERS, VACCINATION
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from pet
    where ID = #{id,jdbcType=INTEGER}
  </select>
  <select id="getAll" resultMap="BaseResultMap">
  	select * from Pet
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from pet
    where ID = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.pet.bean.Pet" >
    insert into pet (ID, PETNAME, AGE, 
      STATUS, MED_HISTORY, FEATHERS, 
      VACCINATION)
    values (#{id,jdbcType=INTEGER}, #{petname,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{status,jdbcType=VARCHAR}, #{medHistory,jdbcType=VARCHAR}, #{feathers,jdbcType=VARCHAR}, 
      #{VACCINATION,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.pet.bean.Pet" >
    insert into pet
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="petname != null" >
        PETNAME,
      </if>
      <if test="age != null" >
        AGE,
      </if>
      <if test="status != null" >
        STATUS,
      </if>
      <if test="medHistory != null" >
        MED_HISTORY,
      </if>
      <if test="feathers != null" >
        FEATHERS,
      </if>
      <if test="vaccination != null" >
        VACCINATION,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="petname != null" >
        #{petname,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        #{status,jdbcType=VARCHAR},
      </if>
      <if test="medHistory != null" >
        #{medHistory,jdbcType=VARCHAR},
      </if>
      <if test="feathers != null" >
        #{feathers,jdbcType=VARCHAR},
      </if>
      <if test="vaccination != null" >
        #{vaccination,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.pet.bean.Pet" >
    update pet
    <set >
      <if test="petname != null" >
        PETNAME = #{petname,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        AGE = #{age,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        STATUS = #{status,jdbcType=VARCHAR},
      </if>
      <if test="medHistory != null" >
        MED_HISTORY = #{medHistory,jdbcType=VARCHAR},
      </if>
      <if test="feathers != null" >
        FEATHERS = #{feathers,jdbcType=VARCHAR},
      </if>
      <if test="vaccination != null" >
        VACCINATION = #{vaccination,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.pet.bean.Pet" >
    update pet
    set PETNAME = #{petname,jdbcType=VARCHAR},
      AGE = #{age,jdbcType=INTEGER},
      STATUS = #{status,jdbcType=VARCHAR},
      MED_HISTORY = #{medHistory,jdbcType=VARCHAR},
      FEATHERS = #{feathers,jdbcType=VARCHAR},
      vaccination = #{vaccination,jdbcType=VARCHAR}
    where ID = #{id,jdbcType=INTEGER}
  </update>
</mapper>

(3)spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
        http://www.springframework.org/schema/context    
        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
        http://www.springframework.org/schema/mvc    
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
        <!-- 自动扫描 -->  
        <context:component-scan base-package="com.pet">
        	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        </context:component-scan>  
        <!-- 引入配置文件 -->  
        <bean id="propertyConfigurer"  
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
            <property name="location" value="classpath:jdbc.properties" />  
        </bean>  
      
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
            destroy-method="close">  
            <property name="driverClassName" value="${db.driverClassName}" />  
            <property name="url" value="${db.url}" />  
            <property name="username" value="${db.username}" />  
            <property name="password" value="${db.password}" />  
        </bean>  
      
        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
            <property name="dataSource" ref="dataSource" />  
            <!-- 自动扫描mapping.xml文件 -->  
            <property name="mapperLocations" value="classpath*:com/pet/mapper/*.xml"></property> 
            <--如果PetMapper.java文件和PetMapper.xml文件在同一目录就用上面的自动扫描即可,不需要下面的这个configLocation来配置目录。
              如果不在同一目录,则上面的mapperlocation不要,使用下面的configlocation配置相应目录
            -->
           <property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean> <!-- Mapper扫描包--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.pet.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> </beans>



(4)mybatis-config.xml(根据此项更改spring-mybatis.xml)

注意:当*Mapper.xml和对应的*Mapper.java接口在同一个目录下面的时候,此时这个配置文件可以省略

           如果不在同一目录,这里需要在mapper里面配上其目录


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="*Mapper.xml的目录"/>
    </mappers>
</configuration>


(5)junit测试

@Test
    public void findUserByIdTest2(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mybatis.xml");
        PetMapper petMapper = (PetMapper) ctx.getBean("petMapper");//petMapper和PetMapper对应
        List<Pet> pet = petMapper.getAll();
        System.out.println(pet);
    }