mybatis 之 mybatis整合spring

  1. mybatis整合spring

    a) 新建java项目

    b) 导入jar包,特别需要注意导入mybatis 和 spring 的整合包

    aopalliance.jar
    aspectjweaver.jar
    commons-logging-1.1.1.jar
    mybatis-3.2.7.jar
    mybatis-spring-1.2.3.jar
    mysql-connector-java-5.1.20-bin.jar
    spring-aop-4.1.6.RELEASE.jar
    spring-aspects-4.1.6.RELEASE.jar
    spring-beans-4.1.6.RELEASE.jar
    spring-context-4.1.6.RELEASE.jar
    spring-core-4.1.6.RELEASE.jar
    spring-expression-4.1.6.RELEASE.jar
    spring-jdbc-4.1.6.RELEASE.jar
    spring-tx-4.1.6.RELEASE.jar
    spring-web-4.1.6.RELEASE.jar
    spring-webmvc-4.1.6.RELEASE.jar
    c)配置mybatis核心配置文件
    <configuration>
        <properties resource="db.properties"></properties>
        <settings>
            <setting name="cacheEnabled" value="true"/>
        </settings>
        <typeAliases>
            <package name="cn.wh.vo"/>
        </typeAliases>
        <mappers>
            <mapper resource="cn/wh/mapper/UserMapper.xml" />
        </mappers>
    </configuration>

    d) 编写vo:

    public class User {
        private int id;
        private String name;
        private String pwd;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    }

    e) 编写dao接口

    public interface UserDao {
        public List<User> findAll();
    }

     f) 编写mapper映射文件

  <mapper namespace="cn.wh.mapper.UserMapper">
      <select id="findAll" resultType="User">
          select * from t_user
      </select>
  </mapper>

     g) 编写dao的实现类

public class UserDaoImpl implements UserDao{
    private SqlSession sqlSession;
    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List<User> findAll() {
        return sqlSession.selectList("cn.wh.mapper.UserMapper.findAll");
    }
}

     h) 编写service接口及其实现类

public class UserServiceImpl implements UserService{
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}

     i) 编写spring的配置文件

<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:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql:///test"/>
      <property name="username" value="root"/>
      <property name="password" value="1111"/>
  </bean>
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="configLocation" value="classpath:mybatis.cfg.xml"/>
  </bean>
  <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
  </bean>
  <!-- 配置声明式事务 -->
 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"></property>
 </bean>
  <!-- 配置事务通知 -->
  <tx:advice id="txAdvice" transaction-manager="txManager">
      <tx:attributes>
          <!-- 表示以save开头的方法都需要事务      
          propagation  表示事务的传播特性 
          REQUIRED  查看当前是否有事务,如果有,使用当前事务,如果没有开启新事务
          -->
          <tx:method name="save*" propagation="REQUIRED"/>
          <tx:method name="update*" propagation="REQUIRED"/>
          <tx:method name="find*" read-only="true"/>
          <tx:method name="*" propagation="REQUIRED"/>
      </tx:attributes>
  </tx:advice>
  <!-- 配置事务aop  -->
    <aop:config>
        <!--expression  指明事务在哪里起作用
        第一个* 表示所有返回值 
        第二个* 表示所有类
        第三个* 表示类中的所有方法
        .. 表示所有参数
          -->
        <aop:pointcut expression="execution(* cn.wh.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config> 
    <!-- 自动扫描 指定包下及其子包下的所有类中注解,并根据注解完成指定工作 --> 
      <bean id="userDao" class="cn.wh.dao.impl.UserDaoImpl">
          <property name="sqlSession" ref="sqlSession"></property>
      </bean>
      <bean id="userService" class="cn.wh.service.impl.UserServiceImpl">
          <property name="userDao" ref="userDao"></property>
      </bean>
  
</beans>

     j) 测试

@Test
    public void testFindAll(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
        UserService userService = ac.getBean(UserService.class);
        List<User> list = userService.findAll();
        System.out.println(list.size());
    }
  • 不需要使用mybatis的配置文件,那么需要在配置sqlSessionFactory时,将所需信息配置到是spring中。
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <property name="typeAliasesPackage" value="cn.wh.vo"/>
          <property name="mapperLocations">
              <list>
                  <value>classpath:cn/wh/mapper/UserMapper.xml</value>
              </list>
          </property>
  • 不需要dao的实现,使用代理来生成的方式,UserService.java
    public class UserServiceImpl implements UserService{
        private UserMapper userMapper;
        public void setUserMapper(UserMapper userMapper) {
            this.userMapper = userMapper;
        }
        @Override
        public List<User> findAll() {
            return userMapper.findAll();
        }
    }
  • 配置文件为
    <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:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd 
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
          <property name="url" value="jdbc:mysql:///test"/>
          <property name="username" value="root"/>
          <property name="password" value="1111"/>
      </bean>
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <property name="typeAliasesPackage" value="cn.wh.vo"/>
          <property name="mapperLocations">
              <list>
                  <value>classpath:cn/wh/mapper/UserMapper.xml</value>
              </list>
          </property>
      </bean>
      <!-- 配置声明式事务 -->
     <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
     </bean>
      <!-- 配置事务通知 -->
      <tx:advice id="txAdvice" transaction-manager="txManager">
          <tx:attributes>
              <!-- 表示以save开头的方法都需要事务      
              propagation  表示事务的传播特性 
              REQUIRED  查看当前是否有事务,如果有,使用当前事务,如果没有开启新事务
              -->
              <tx:method name="save*" propagation="REQUIRED"/>
              <tx:method name="update*" propagation="REQUIRED"/>
              <tx:method name="find*" read-only="true"/>
              <tx:method name="*" propagation="REQUIRED"/>
          </tx:attributes>
      </tx:advice>
      <!-- 配置事务aop  -->
        <aop:config>
            <!--expression  指明事务在哪里起作用
            第一个* 表示所有返回值 
            第二个* 表示所有类
            第三个* 表示类中的所有方法
            .. 表示所有参数
              -->
            <aop:pointcut expression="execution(* cn.wh.service.impl.*.*(..))" id="pointcut"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
        </aop:config> 
        <!-- 自动扫描 指定包下及其子包下的所有类中注解,并根据注解完成指定工作 --> 
          <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
              <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
              <property name="mapperInterface" value="cn.wh.mapper.UserMapper"/>
          </bean>
          <bean id="userService" class="cn.wh.service.impl.UserServiceImpl">
              <property name="userMapper" ref="userMapper"></property>
          </bean>
      
    </beans>
  • 所有mapper的实现都自动生产成,需要接口和映射文件在同一个包下,文件名相同,方法名和statement的id名称相同,配置文件为:
    <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:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd 
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
          <property name="url" value="jdbc:mysql:///test"/>
          <property name="username" value="root"/>
          <property name="password" value="1111"/>
      </bean>
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <property name="typeAliasesPackage" value="cn.wh.vo"/>
          <property name="mapperLocations">
              <list>
                  <value>classpath:cn/wh/mapper/UserMapper.xml</value>
              </list>
          </property>
      </bean>
      <!-- 自动扫描包,并且生成mapper的实现类,生成的bean的名称为mapper接口的首字母小写 -->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="basePackage" value="cn.wh.mapper"/>
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
      </bean>
      <!-- 配置声明式事务 -->
     <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
     </bean>
      <!-- 配置事务通知 -->
      <tx:advice id="txAdvice" transaction-manager="txManager">
          <tx:attributes>
              <!-- 表示以save开头的方法都需要事务      
              propagation  表示事务的传播特性 
              REQUIRED  查看当前是否有事务,如果有,使用当前事务,如果没有开启新事务
              -->
              <tx:method name="save*" propagation="REQUIRED"/>
              <tx:method name="update*" propagation="REQUIRED"/>
              <tx:method name="find*" read-only="true"/>
              <tx:method name="*" propagation="REQUIRED"/>
          </tx:attributes>
      </tx:advice>
      <!-- 配置事务aop  -->
        <aop:config>
            <!--expression  指明事务在哪里起作用
            第一个* 表示所有返回值 
            第二个* 表示所有类
            第三个* 表示类中的所有方法
            .. 表示所有参数
              -->
            <aop:pointcut expression="execution(* cn.wh.service.impl.*.*(..))" id="pointcut"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
        </aop:config> 
          <bean id="userService" class="cn.wh.service.impl.UserServiceImpl">
              <property name="userMapper" ref="userMapper"></property>
          </bean>
    </beans>
原文地址:https://www.cnblogs.com/forever2h/p/6796784.html