MyBatis-Spring 整合详解(三)

MyBatis用纯程序的方式在main 函数中得到数据库连接  直接读mybatis-config.xml文件;

MyBatis-Spring:在spring容器中加载MyBatis;

MyBatis整合到Spring 配置步骤:  

1.SqlSessionFactory必须创建  并且传递数据源 这是mybatis 的基础bean ;

2.直接用mapper接口去做查询;

                  a.MapperFactoryBean

                  b.MapperScannerConfiger

        这两种都需要SqlSessionFactory   b 方法若只有一个数据源可以不注入SqlSessionFactory,但必须创建SqlSessionFactory的Bean;

3.使用sqlsession 做数据操作(不让mapper直接操作);

            a.sqlsessionTemplate                需要注入SqlSessionFactory  然后把此类注入给业务类使用   --封装

            b.继承sqlsessionDaoSupport      子类需要注入SqlSessionFactory,然后直接使用sqlsession操作  --封装

             mapper  可以直接操作数据库(针对一个mapper)

             sqlsession  可以操作多个mapper

SqlSessionFactory属性:JDBC 的 DataSource   和configLocation

SqlSessionFactoryBean 实现了 Spring 的 FactoryBean 接口,说明了由 Spring 最终创建的 bean 不是 SqlSessionFactoryBean 本身, 。 而是工厂类的 getObject()返回的方法的结果。这种情况下,Spring 将会在应用启动时为你 创建 SqlSessionFactory 对象,然后将它以 SqlSessionFactory 为名来存储;

    

       1.引入mybatis 的bean:         

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

  

         2.注入sqlSessionFactory 传入数据源:

          

       3.声明mapper接口:(注入映射器

                  映射器类必须是一个接口,而不是具体的实现类

       

          

     

    4.mapper 注入到service/dao(操作数据--下面有sqlsession 具体操作方法):

package com.spring.service;

import com.spring.entry.Students;
import com.spring.mybatis.StudentMapper;
//import com.spring.util.JdbcUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class StudentService <T> {

    @Autowired
    private StudentMapper studentMapper;

    public StudentMapper getStudentMapper() {
        return studentMapper;
    }

    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }
    public List<Students> queryStudentList(Students t) throws Exception {

        String sql="select * from students where 1=1 ";
        List<Students> studentList=studentMapper.seletestudentmapper();
        return studentList;
}

    5.sqlsession操作数据:

      MyBatis 中可使用 SqlSessionFactory 来创建 SqlSession  

      MyBatis-Spring 之后, 你不再需要直接使用 SqlSessionFactory 了,因为你的 bean 可以通过一个线程安全的 SqlSession 来注入,基于 Spring 的事务配置 来自动提交,回滚,关闭 session。通常不直接使用 SqlSession。 在大多数情况下 MapperFactoryBean, 将会在 bean 中注入所需要的映射器。

sqlSession操作两种方式:(dao层)

    2个工具类 用在 dao层  不直接用sqlsession 用工具类实现;

sqlsessionFactory 注入到 该  工具类中就可以用了 得到一个sqlsession   将其注入到dao层  就可以操作mapper了  dao层只是为了不直接让方法接触mapper( 提前封装好操作方法 不让它去接触mapper SQLsession   封装dao 给 service用)

1.SqlSessionTemplate:

       实现了 SqlSession 接口,这个类负责管理 MyBatis 的 SqlSession, 调用 MyBatis 的 SQL 方法 线程安全

      

public class StudentDao<Students> {

 @Autowired
 private SqlSession sqlSession;

 private StudentMapper studentMapper;

 public SqlSession getSqlSession() {
  return sqlSession;
 }

 public void setSqlSession(SqlSession sqlSession) {
  this.sqlSession = sqlSession;
 }

 public List<Students> query()
 {

  //注入mapper  直接可以调用方法
  studentMapper.seletestudentmapper();
  //注入sqlsession 就可以得到mapper   然后在掉哟个方法
  //sqlSession.getMapper(StudentMapper.class);

  return null;

 }
}

2.SqlSessionDaoSupport:

     抽象 的支 持 类, 提供 SqlSession 。 调 用 getSqlSession()方法得到SqlSessionTemplate,之后可以用于执行 SQL 方法, 

     继承 SqlSessionDaoSupport   需要在实现类上注入sqlsessionFactory

public class TeacherDao<Teacher> extends SqlSessionDaoSupport {
    
    //可以再封装一层 进行注入
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public List<Teacher> query() {

        this.getSqlSession().getMapper(TeacherMapper.class);
        return null;
    }
}

事务:(事务传播机制很复杂)

 

1.标准配置

    事务管理器 利用dataSource管理 与sqlSessionFactory的数据源一致 既可以应用的spring的事务管理(控制事务@Transactional)-开启spring的事务处理;
       

 2.容器管理事务

 3.编程式事务管理


 

注入映射器两种方式:

  应用动态代理的实现:MapperFactoryBean ,可直接注入数据映射器接口到你的 service 层 bean 中

1.MapperFactoryBean(映射器是一个接口 不是具体实现类)

        

2.MapperScannerConfigurer包下找,

    没 有 必 要 去 指 定 SqlSessionFactory 或 SqlSessionTemplate , 因 为 MapperScannerConfigurer 将会创建 MapperFactoryBean,之后自动装配。

      

 

如果mapper.xml 与mapper接口类不再同一个包下?(两种方式)

   1.mapperLocations

       这会从类路径下加载在 sample.config.mappers 包和它的子包中所有的 MyBatis 映射器 XML 文件;

     

   2.包的方式:(扫描包下所有mapper.xml)

       

 

applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
       default-lazy-init="false">

    <description>Spring公共配置</description>

    <!--数据库连接池-->
    <bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>

        <property name="initialSize" value="0"></property>
        <property name="minIdle" value="10"></property>
    </bean>

    <!--SqlSessionFactoryBean  不会返回本身实例  返回sqlSessionFactory的实例-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource2"></property>

        <!--如果mapper.xml 与mapper类不再同一个包下   配置文件对应在class path下的mybatis下
        <property name="mapperLocations" value="classpath*:mybatis/*.xml"></property>
        <property name="configLocation" value="classpath*:mybatis-config.xml"></property>-->
    </bean>
    
    <!--包下扫描mapper  不用配置各个mapper  直接注入mapper就可以用-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.spring.mybatis"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!--MapperFactoryBean  不会返回本身实例  返回studentMapper的实例
    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.spring.mybatis.StudentMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>-->
    
    <!--事务管理器  利用dataSource管理 与sqlSessionFactory的数据源一致 既可以应用的spring的事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       
        <property name="dataSource" ref="dataSource2"></property>
    </bean>

    <!--SqlSession工具类-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

</beans>

ps:MyBatis-Spring官方文档:http://www.mybatis.org/spring/zh/

猜你喜欢

转载自blog.csdn.net/weixin_42249629/article/details/81712499