Mybatis和Spring整合的三种方法

2017-04-23 10:54

首先在spring-mybatis.xml中添加以下内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
 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-3.1.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hua.saf" />
    <!-- 引入配置文件 -->
    <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="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
        <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
    </bean>

方式1:
在上述spring-mybatis.xml中添加

 <!-- DAO接口所在包名,Spring会自动查找其下的类 ,包下的类需要使用@MapperScan注解,否则容器注入会失败 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hua.saf.*" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

配置UserMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
-->
<mapper namespace="com.hua.saf.dao.UserDao">
  <!--
  在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复,
  使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
  resultType="com.hua.saf.User"就表示将查询结果封装成一个User类的对象返回,User类就是t_user表所对应的实体类
  -->
  <!-- 根据id查询得到一个user对象-->
  <select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
    select * from t_user where id=#{id}
  </select>
</mapper>

接着创建Dao

/**
* 这里的@MapperScan就是上面所讲的Mapper扫描器中所需要的配置,会自动生成代理对象。
* 注意,接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样,因为生成的
* 动态代理,会根据这个匹配相应的Sql语句执行。
* */
@MapperScan
public interface UserDao {
  //此处的方法名必须和mapper中的映射文件中的id同名
  //回去映射文件中通过com.hua.saf.dao.UserDao.getUser,即this.getClass().getName()+".getUser"
  public User getUser(int id);
}

创建Serviece类

@Service("userService")
public class UserServiceImpl implements IUserService {

@Resource
private UserDao userDao;

  public User getUser(int id) {
    return userDao.getUser(id);
  }
}

方式2:采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
  mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
在spring-mybatis.xml中添加

<!-- mybatis spring sqlSessionTemplate,使用时直接让spring注入即可 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

sqlMapConfig.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>  
    <typeAliases>
        <typeAlias type="com.hua.saf.pojo.User" alias="User" />
    </typeAliases>
</configuration>

User类

public class User {

    private int id;
    private String username;
    private String password;
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

UserDao类

@Repository
public class UserDao{

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    public User getUser(int id) {
        return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);
    }   
}

UserService类

@Service
public class UserService{

    @Resource
    private UserDao userDao;

    public User getUser(int id) {
        return userDao.getUser(id);
    }
}

方式3:采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
sqlMapConfig.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>  
    <typeAliases>
        <typeAlias type="com.hua.saf.pojo.User" alias="User" />
    </typeAliases>
</configuration>

User类

public class User {

    private int id;
    private String username;
    private String password;
    private int age;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

UserDao类

@Repository
public class UserDao extends SqlSessionDaoSupport{

    public User getUser(int id) {
        return this.getSqlSession().selectOne(this.getClass().getName() + ".getUser", 1);
    }
  //使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强
  //也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到少个,多个dao就很麻烦。
  //<bean id="userDao" class="com.hua.saf.dao.UserDao">
  // <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  //</bean>
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        // TODO Auto-generated method stub
        super.setSqlSessionFactory(sqlSessionFactory);
    }
}

UserService类

@Service
public class UserService{

    @Resource
    private UserDao userDao;

    public User getUserss(int id) {
        return userDao.getUser(1);
    }
}