IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> MyBatis与Spring的整合 -> 正文阅读

[Java知识库]MyBatis与Spring的整合

MyBatis与Spring的整合

整合环境搭建

准备所需JAR包

1、Spring框架所需的JAR包
Spring框架所需要准备的JAR包共10个,其中包括:4个核心模块JAR,AOP开发使用的JAR,JDBC和事务的JAR(其中核心容器依赖的commons-logging的JAR在MyBatis框架的lib包中已经包含,所有这里不必引入),具体如下
aopalliance-1.0.jar
aspectjweaver-1.8.10.jar
spring-aop-4.3.6.RELEASE.jar
spring-aspects-4.3.6.RELEASE.jar
spring-beans-4.3.6.RELEASE.jar
spring-context-4.3.6.RELEASE.jar
spring-core-4.3.6.RELEASE.jar
spring-expression-4.3.6.RELEASE.jar
spring-jdbc-4.3.6.RELEASE.jar
spring-tx-4.3.6.RELEASE.jar
2、MyBatis框架所需的JAR包
MyBatis框架所需要准备的JAR包共13个,其中包括:核心包mybatis-3.4.2.jar以及其解压文件夹中lib目录中的所有JAR
ant-1.9.6.jar
ant-launcher-1.9.5.jar
asm-5.1.jar
cglib-3.2.4.jar
commons-logging-1.2.jar
javassist-3.21.0-GA.jar
log4j-1.2.17.jar
log4j-api-2.3.jar
log4j-core-2.3.jar
mybatis-3.4.2.jar
ognl-3.1.12.jar
slf4j-api-1.7.22.jar
slf4j-log4j12-1.7.22.jar
3、MyBatis与Spring整合的中间JAR
由于MyBatis3在发布之前,Spring3就已经开发完成,而Spring团队既不想发布基于MyBatis3的非发布版本的代码,也不想长时间的等待,所以Spring3以后,就没有对MyBatis3进行支持。为了满足MyBatis用户对Spring框架的需求,MyBatis社区自己开发了一个用于整合这两个框架的中间件——MyBatis-Spring、
这里使用的是mybatis-spring-1.3.1.jar
https://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.3.1
4、数据库驱动JAR包
mysql-connector-java-5.1.40-bin.jar
5、数据源所需JAR包
commons-dbcp2-2.1.1.jar
commons-pool2-2.4.2.jar

编写配置文件

1)在Eclipse中创建一个chapter10web项目
2)在src目录下,分别创建db.properties文件、Spring的配置文件以及MyBatis的配置文件
db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
	<context:property-placeholder location="classpath:db.properties"/>
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="maxTotal" value="${jdbc.maxTotal}"/>
		<property name="maxIdle" value="${jdbc.maxIdle}"/>
		<property name="initialSize" value="${jdbc.initialSize}"/>
	</bean>
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:mybatis-config.xml"/>
	</bean>
</beans>

首先定义了读取properties文件的配置,然后配置了数据源,接下来配置了事务管理器并开启了事务注解,最后配置了MyBatis工厂来与Spring整合。其中,MyBatis工厂的作用就是构建SqlSessionFactory,它是通过mybatis-spring包中提供的org.mybatis.spring.SqlSessionFactoryBean类来配置的。通常,在配置时需要提供两个参数:一个是数据源,另一个是MyBatis的配置文件路径。这样Spring的IoC容器就会在初始化id为sqlSessionFactory的Bean时解析MyBatis的配置文件,并于数据源一同保存到spring的Bean里。

mybatis-config.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>
		<package name="com.ex.po"/>
	</typeAliases>
	<mappers>
	
	</mappers>
</configuration>

由于在Spring中已经配置了数据源信息,所以在MyBatis的配置文件中就不再需要配置数据源信息。
此外还需要创建log4j.properties文件

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.ex=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

传统DAO方式的开发整合

采用传统DAO开发方式进行MyBatis与Spring框架的整合时,我们需要编写DAO接口以及接口的实现类,并且需要向DAO实现类中注入SqlSessionFactory,然后在方法体内通过SqlSessionFactory创建SqlSession。为此,我们可以使用mybatis-spring包中所提供的SqlSessionTemplate类或SqlSessionDaoSupport类来实现此功能
1、SqlSessionTemplate
是mybatis-spring的核心类,它负责管理MyBatis的SqlSession。调用MyBatis的SQL方法。当调用SQL方法时,SqlSessionTemplate将会保证使用SqlSession和当前Spring的事务是相关的。它还管理SqlSession的生命周期,包含必要的关闭、提交和回调操作。
2、SqlSessionDaoSupport
是一个抽象支持类,它继承了DaoSupport类,主要是作为DAO的基类来使用。可以通过SqlSessionDaoSupport类的getSqlSession()方法来获取所需的SqlSession。

实现持久层

在src目录下,创建一个com.ex.po包,并在包中创建持久化类Customer

package com.ex.po;
public class Customer {
	private Integer id;
	private String username;
	private String jobs;
	private String phone;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getJobs() {
		return jobs;
	}
	public void setJobs(String jobs) {
		this.jobs = jobs;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	@Override
	public String toString() {
		return "Customer [id=" + id + ", username=" + username + ", jobs="
				+ jobs + ", phone=" + phone + "]";
	}
}

2)在com.ex.po包中,创建映射文件CustomerMapper.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.ex.po.CustomerMapper">
	<select id="findCustomerById" parameterType="int"
		resultType="customer">
		select * from t_customer where id=#{id};
	</select>
</mapper>

3)在MyBatis的配置文件mybatis-config.xml中,配置映射文件CustomerMapper.xml的位置

<mapper resource="com/ex/po/CustomerMapper.xml"/>

实现DAO层

1)在src目录下,创建一个com.ex.dao包,并在包中创建接口CustomerDao,在接口中编写一个通过id查询客户的方法findCustomerById()

package com.ex.dao;

import com.ex.po.Customer;

public interface CustomerDao {
	public Customer findCustomerById(Integer id);
}

2)创建一个com.ex.dao.impl包,在包中创建CustomerDao接口的实现类CustomerDaoImpl

package com.ex.dao.impl;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.ex.dao.CustomerDao;
import com.ex.po.Customer;
public class CustomerDaoImpl extends SqlSessionDaoSupport
		implements CustomerDao {
	@Override
	public Customer findCustomerById(Integer id) {
		return this.getSqlSession().selectOne("com.ex.po"
				+ ".CustomerMapper.findCustomerById", id);
	}
}

CustomerDaoImpl 类继承了SqlSessionDaoSupport类,并实现了CustomerDao 接口。其中,SqlSessionDaoSupport类在使用时需要一个SqlSessionFactory或一个SqlSessionTemplate对象,所以需要通过Spring给SqlSessionDaoSupport类的子类对象注入一个SqlSessionFactory或SqlSessionTemplate。这样,在子类中就能通过调用getSqlSession()方法来获取SqlSession对象,并使用SqlSession对象中的方法了。
3)在Spring的配置文件applicationContext.xml中,编写实例化CustomerDaoImpl的配置

	<bean id="customerDao" class="com.ex.dao.impl.CustomerDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>

整合测试

创建一个com.ex.test包,在包中创建测试类DaoTest

package com.ex.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ex.dao.CustomerDao;
import com.ex.po.Customer;

public class DaoTest {
	@Test
	public void findCustomerByIdDaoTest(){
		ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerDao customerDao=(CustomerDao) act.getBean("customerDao");
		Customer customer=customerDao.findCustomerById(1);
		System.out.println(customer);
	}
}

在这里插入图片描述
上述方法中,我们采用的是根据容器中Bean的id来获取指定Bean的方式。我们可以通过另一种获取Bean的方式。

CustomerDao customerDao=act.getBean(CustomerDao.class);

这样在获取Bean的实例时,就不再需要进行强制类型转换了。

Mapper接口方式的开发整合

在MyBatis+Spring的项目中,虽然使用传统的DAO开发方式可以实现所需功能,但是采用这种方式在实现类中会出现大量的重复代码,在方法中也需要指定映射文件中执行语句的id,并不能保证编写时id的正确性(运行时才能知道)。

基于MapperFactoryBean的整合

MapperDactoryBean是MyBaits-Spring团队提供的一个用于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数。
1)mapperInterface:用于指定接口。
2)sqlSessionFactory:用于指定SqlSessionFactory。
3)sqlSession:用于指定SqlSessionTemplate。如果与sqlSessionFactory同时设定,则只会启用sqlSessionFactory。
1)创建com.ex.mapper包,然后包中创建CustomerMapper接口以及对应的映射文件

package com.ex.mapper;
import com.ex.po.Customer;
public interface CustomerMapper {
	public Customer findCustomerById(Integer id);
}
<?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.ex.mapper.CustomerMapper">
	<select id="findCustomerById" parameterType="int"
		resultType="customer">
		select * from t_customer where id=#{id}
	</select>
</mapper>

这两个文件与之前CustomerDao接口以及CustomerMapper.xml的实现代码基本相同。
2)在MyBatis的配置文件中,引入新的映射文件

		<mapper resource="com/ex/mapper/CustomerMapper.xml"/>

注:使用Mapper接口动态开发时,如果完全遵循了编写规范,那么在配置文件中可以不引入映射文件。
3)在Spring的配置文件中,创建一个id为customerMapper的Bean

	<bean id="customerMapper"
		class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.ex.mapper.CustomerMapper"/>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>

4)在测试类DaoTest中,编写测试方法findCustomerByIdMapperTest()

	@Test
	public void findCustomerByIdMapperTest(){
		ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerMapper customerMapper=act.getBean(CustomerMapper.class);
		Customer customer=customerMapper.findCustomerById(1);
		System.out.println(customer);
	}

在这里插入图片描述
注:Mapper接口编程方式需要满足的规范
1)Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致。
2)Mapper.xml文件中的namespace与Mapper接口的类路径相同(即接口文件和映射文件放在同一包中)
3)Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同。
4)Mapper接口中方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同
5)Mapper接口方法的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同。

基于MapperScannerConfigurer的整合

在实际的项目中,DAO层会包含很多接口,如果每个接口都想上述那样配置,那么不但会增加工作量,还会使得Spring配置文件非常臃肿。为此,MyBatis-Spring团队提供了一种自动扫描的形式来配置MyBatis中的映射器——采用MapperScannerConfigurer类。
MapperScannerConfigurer类在Spring配置文件中使用时可以配置以下几个属性
1)basePackage:指定映射接口文件所在的包路径,当需要扫描多个包时可以使用分号或逗号作为分隔符。指定包路径后,会扫描该包及其子包中的所有文件。
2)annotationClass:指定了要扫描的注解名称,只有被注解标识的类才会被配置为映射器。
3)sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFacotry的Bean名称
4)sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义此属性,则sqlSessionFactoryBeanName将不起作用。
5)makerInterface:指定创建映射器的接口。
MapperScannerConfigurer的使用非常简单,只需要在Spring的配置文件中编写

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ex.mapper"/>
	</bean>

可以看到这里不需要引入sqlSessionFactory,因为当配置文件中只有一个sqlSessionFactory时,MapperScannerConfigurer会自动装配。

测试事务

1)在CustomerMapper接口中,编写测试方法addCustomer()

public void addCustomer(Integer id);

编写完接口中的方法后,在映射文件CustomerMapper.xml中编写执行插入操作的SQL配置

	<insert id="addCustomer" parameterType="customer">
		insert into t_customer(username,jobs,phone)
		values(#{username},#{jobs},#{phone})
	</insert>

2)在src目录下,创建一个com.ex.service包,并在包中创建CustomerService,在接口中编写一个添加客户的方法addCustomer()

package com.ex.service;
import com.ex.po.Customer;
public interface CustomerService {
	public void addCustomer(Customer customer);
}

3)在src目录下,创建一个com.ex.service.impl包,并在包中创建CustomerService接口的实现类CustomerServiceImpl

package com.ex.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ex.mapper.CustomerMapper;
import com.ex.po.Customer;
import com.ex.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private CustomerMapper customerMapper;
	@Override
	public void addCustomer(Customer customer) {
		this.customerMapper.addCustomer(customer);
		int i=1/0;
	}

}

4)在Spring的配置文件中,编写开启注解扫描的配置代码

<context:component-scan base-package="com.ex.service"/>

5)在com.ex.test包中,创建测试类TransactionTest

package com.ex.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ex.po.Customer;
import com.ex.service.CustomerService;

public class TransactionTest {
	@Test
	public void CustomerServiceTest(){
		ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerService customerService=act.getBean(CustomerService.class);
		Customer customer=new Customer();
		customer.setUsername("zhangsan");
		customer.setJobs("manager");
		customer.setPhone("13233334444");
		customerService.addCustomer(customer);
	}
}

在这里插入图片描述
在这里插入图片描述
可以看到新记录没有插入。

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-08-20 14:57:12  更:2021-08-20 14:59:06 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 5:18:08-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码