Spring框架整合Mybatis持久层框架

Spring对mybatis的优势

下面是spring jdbc的数据库操作(核心部分):

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        
        <property name="url" value="jdbc:mysql://localhost:3306/db_spring"/>
        
        <property name="username" value="root"/>
        <property name="password" value=""/>

    bean>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager">tx:annotation-driven>
    <context:component-scan base-package="com.ssm.jdbc"/>
    

```java
public class JdbcTemplateTest {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("resources/applicationContext.xml");
        //获取实例
        JdbcTemplate jdbcTemplate= (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        //使用execute()方法执行sql语句,创建用户表
        jdbcTemplate.execute("create table user("+"id  int primary key auto_increment,"+"username varchar(10),"+"password varchar(10))");

    }

sql融合在代码中,不方便维护和修改,而mybatis将sql提取出来放在Mapper.xml中通过dao层的接口去实现,只需要在映射文件中配置一些基本sql语句实现业务,配置也比spring jdbc简单了许多。

环境配置

  • maven项目导入相关依赖,包括数据库驱动,mybatis工具包。
<dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>
  • 创建mybatis配置文件 mybatis-config.xml


<configuration>
  
configuration>

连接信息可以指直接在配置文件中写入,也可以创建properties文件然后导入xml配置文件。

  • 添加Spring依赖
<dependency>
   <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.2.19.RELEASEversion>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aspectsartifactId>
    <version>5.2.19.RELEASEversion>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.2.19.RELEASEversion>
dependency>


  • 创建Spring核心配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

   <context:annotation-config/>
   

beans>

  • 导入mybatis与spring通信的依赖mybatis-spring
<dependency>
   <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.3.2version>
dependency>
  • 整合德鲁伊(Druid)连接池

Druid是一个JDBC组件,它包括三部分: DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。 DruidDataSource 高效可管理的数据库连接池。 SQLParser 对sql的支持。
Spring框架整合Mybatis持久层框架_第1张图片


<dependency>
   <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.24version>
dependency>

<bean id="DataSource" class="com.alibaba.druid.pool.DruidDataSource" scope="singleton">
        <property name="driver" value="">property>
        <property name="url" value="">property>
        <property name="username" value="">property>
        <property name="password" value="">property>
        
        <property name="initialSize" value="">property>
        <property name="minIdle" value="">property>
        <property name="maxActive" value="">property>
        <property name="maxWait" value="">property>
    bean>

druid有整合了jdbc,就不需要jdbc或者mybatis提供数据源了,由于spring整合式Spring Data/Acess框架提供了数据源DataSource管理,将druid提供给的数据源交由spring管理,scope要为单例模式

DataSource是数据连接的核心,有数据库密码,url,驱动等属性,有了DataSource就调用框架的接口操作数据库。spring IoC只起管理作用,mybatis使用druid数据源,既优化连接数据库有提供了连接池的支持。

  • spring IoC容器管理数据源DataSource注意scope要为单例模式:
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" scope="singleton">
        <property name="driver">property>
        <property name="url">property>
        <property name="username">property>
        <property name="password">property>

        <property name="initialSize" value="">property>
        <property name="minIdle" value="">property>
        <property name="maxActive" value="">property>
        <property name="maxWait" value="">property>
    bean>

连接信息可以直接在xml中配置也可以新建properties文件,在导入到xml:

<context:property-placeholder location="classpath:xxx/xxx.properties">context:property-placeholder>

Spring管理Mybatis工厂类

经过上面的配置已将DataSource整合到IoC容器中,但mybatis还没有整合,核心步骤就是将Mybatis的工厂类交由IoC容器管理。

Mybatis操作数据的核心:

  • DataSource
  • SqlSessionFactory
  • SqlSession
  • Mapper

DataSource没用mybatis自带的而是druid目的是:Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。

SqlSessionFactory需要调用DataSource,再将SqlSessionFactory交由IoC容器管理,就完成整合了。但是SqlSessionFactory是mybatis的接口,不是java的对象没办法直接交由IoC管理,Spring提供了SqlSessionFactoryBean作为SqlSessionFactory的同类型类。同时通过输出流读入mybatis配置文件就能创建创建SqlSessionFactory,再自动装配给或继承就可以交由IoC容器管理了。

Mybatis的SqlSessionFactory创建:

String resource = "xxx/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

导入mybatis-spring工具包使用工具包实现SqlSessionFactoryBean


    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>

更简单的方法:

Spring的SqlSessionFactoryBean对象提供了configLocation属性读入配置文件,同时创建SqlSessionFactory对象,dataSource属性配置DataSource对象,mapperLocation配置Mapper映射等功能完成了再IoC容器中对SqlSessionFactory的创建。

上面mybatis的核心配置文件没有配置参数,依赖SqlSessionFactoryBean接口提供了一些属性用来在IoC容器中对DataSourceMapper等核心功能进行配置。

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
     <property name="dataSource" ref="">property>
     <property name="mapperLocation" value="classpath:xxx.Mapper.xml">property>
     <property name="typeAliasesPackage" value="cms.pojo.mapper">property>
     <property name="configLocation" value="classpath:xxx/mybatis-config.xml">property>
 bean>

在IoC容器创建SqlSessionFactory对象后就将mybatis整合到Spring了。

IoC管理Mapper

IoC容器能管理SqlSessionFactory对象那么也能管理SqlSession对象,同理Mapper映射(dao),并通过自动专配赋值。

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDao {
    ApplicationContext context=new ClassPathXmlApplicationContext("spring配置文件");
    SqlSessionFactory sqlSessionFactory=(SqlSessionFactory) context.getBean("sqlSessionFactory");
    
    //获取到SqlSessionFactory后其他的就是Mybatis的操作了
}

java代码对SqlSessionFactory的操作

SqlSession sqlSession=SqlSessionFactory.openSession();
UserMapper(& UserDao) mapper  = sqlSession.getMapper(UserMapper.class & UserDao.class)   
mapper.select()  //定义的数据库的操作方法

//映射怎么命名自定义

....

实现IoC对Mapper的管理
dao层有很多的Mapper对象,需要将多有的类都交由IoC管理吗?并不需要,mybatis提供了MapperScannerConfigurer类自动包路径下所有的Mapper进行bean生产。当然Mapper是由SqlSession对象调用的,MapperScannerConfigurer需要引用IoC容器的SqlSessionFactory创建SqlSession对象,提供sqlSessionFacotyName属性用来引入IoC容器中的SqlSessionFactory。
还提供basePackage属性指明dao路径。


<bean class=org.mybatis.spring.mapper.MapperScannerConfigurer>
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	<property name="basePackgae" value="dao的路径" />
bean>

从IoC容器获取Mapper

//创建IoC容器
ApplicationContext context=new ClassPathXmlApplicationContext("spring配置文件");

//从容器中获取bean,实现MapperScannerConfigurer后直接获取Mapper对象
UserMapper mapper=(UserMapper) context.getBean("userMapper");  
/*
** 自动将接口的首字母转为小写,映射为接口的bean的id属性
*/

service层封装mapper
dao层和service共同完成ORM模型,service层调用dao层实现业务处理,自动装配实现:

@Service
public class DoUserService implements Userservice{
	@Autowired
	private UserDao userDao;

	public List<User> userList(){
		return userDao.queryUser()  //dao层定义的方法返回用户列表
	}
}

AOP实现声明式事务管理

事务时数据库的基本单元。

  • jdbc模块xml配置事务管理器
 
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="druidDataSource">property>
    bean>


<tx:advice id="" transaction-manager="">
  
tx:advice>

上面的配置只是定义了一个事务管理器,还需要声明管理的方法,声明后该方法对数据的操作就受事务管理的管理。

<aop:config>
       <aop:pointcut id="" expression=""/>
       <aop:advisor advice-ref="">aop:advisor>  
   aop:config>

由此事务xml配置就完成了。

  • 注解完成声明式事务管理

处理xml配置注解也可以完成,当然由配置完的也可以由注解完成。参考Spring基础。


<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="druidDataSource">property>
    bean>


<tx:annotation-driven transaction-manager="" />
@Transaction("隔离级别","传播机制")
public List<User> userList(){...}

你可能感兴趣的:(#,Spring,spring,java-ee,数据库)