文章目录
Sring+MybatisProject的Maven依赖
spring-mybatis.xml配置文件各个标签的作用xml文件注解自动扫描数据库连接基于注解的数据库事务管理MyBatis添加到Spring进行管理
Mapper接口开发整合基于MapperFactoryBean的整合MapperFactoryBean 遵循的规范
基于MapperScannerConfigurer的整合MapperScannerConfigurer在Spring的配置属性:
使用MapperScannerConfigurer进行Mapper文件与接口的装配DAO层Service层SpringJUnit4ClassRunner进行测试
总结
Sring+Mybatis
Spring具有方便继承各种框架的优点,可以与MyBatis等第三方框架进行整合,整合大概就是将MyBatis的配置文件转化成Spring的Bean进行管理,即SqlSessionFactory,从而省去了书写MyBatis配置文件
Project的Maven依赖
使用<properties></properties>进行版本控制
<properties>
<project.build.sourceEncoding>UTF-8
</project.build.sourceEncoding>
<maven.compiler.source>1.7
</maven.compiler.source>
<maven.compiler.target>1.7
</maven.compiler.target>
<junit.version>4.12
</junit.version>
<spring.version>5.2.5.RELEASE
</spring.version>
<mybatis.version>3.5.4
</mybatis.version>
<mybatis.spring.version>2.0.4
</mybatis.spring.version>
<mysql.version>5.1.48
</mysql.version>
<commons-dbcp.version>2.7.0
</commons-dbcp.version>
</properties>
<dependencies>
<dependency>
<groupId>junit
</groupId>
<artifactId>junit
</artifactId>
<version>${junit.version}
</version>
<scope>test
</scope>
</dependency>
<dependency>
<groupId>org.springframework
</groupId>
<artifactId>spring-context
</artifactId>
<version>${spring.version}
</version>
</dependency>
<dependency>
<groupId>org.springframework
</groupId>
<artifactId>spring-test
</artifactId>
<version>${spring.version}
</version>
</dependency>
<dependency>
<groupId>org.springframework
</groupId>
<artifactId>spring-jdbc
</artifactId>
<version>${spring.version}
</version>
</dependency>
<dependency>
<groupId>org.mybatis
</groupId>
<artifactId>mybatis
</artifactId>
<version>${mybatis.version}
</version>
</dependency>
<dependency>
<groupId>org.mybatis
</groupId>
<artifactId>mybatis-spring
</artifactId>
<version>${mybatis.spring.version}
</version>
</dependency>
<dependency>
<groupId>mysql
</groupId>
<artifactId>mysql-connector-java
</artifactId>
<version>${mysql.version}
</version>
</dependency>
<dependency>
<groupId>org.apache.commons
</groupId>
<artifactId>commons-dbcp2
</artifactId>
<version>${commons-dbcp.version}
</version>
</dependency>
<dependency>
<groupId>com.alibaba
</groupId>
<artifactId>druid
</artifactId>
<version>1.1.15
</version>
</dependency>
</dependencies>
spring-mybatis.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/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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.hlq.ch10" />
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</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="typeAliasesPackage" value="com.hlq.ch10.dao" />
<property name="mapperLocations" value="classpath:com/hlq/ch10/dao/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hlq.ch10.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
各个标签的作用
xml文件
注解自动扫描
数据库连接
使用数据库连接池
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<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="initialSize" value="0" />
<property name="maxActive" value="20" />
<property name="minIdle" value="0" />
<property name="maxWait" value="60000" />
<property name="validationQuery" value="SELECT 1" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="25200000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1800" />
<property name="logAbandoned" value="true" />
</bean>
基于注解的数据库事务管理
MyBatis添加到Spring进行管理
Mapper接口开发整合
在MyBatis+Spring的项目中,虽然使用传统的DAO开发方式可以实现所需功能但是采用这种方式在实现类中会出现大量的重复代码在方法中也需要指定映射文件中执行语句的id,并且不能保证编写时id的正确性(运行时才能知道)为此,我们可以使用MyBatis提供的另外一种编程方式,即使用Mapper接口编程
基于MapperFactoryBean的整合
MapperFactoryBean是MyBatis-Spring团队提供的一个用于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数:
mapperInterface:用于指定接口SqlSessionFactory:用于指定SqlSessionFactorySqlSessionTemplate:用于指定SqlSessionTemplate。如果与SqlSessionFactory同时设定,则只会启用SqlSessionTemplate
MapperFactoryBean 遵循的规范
Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致Mapper.xml文件中的namespace与Mapper接口的类路径相同Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同Mapper接口中方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同Mapper接口方法的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同
基于MapperScannerConfigurer的整合
在实际的项目中,DAO层会包含很多接口,如果每一个接口都在Spring配置文件中配置,不但会增加工作量,还会使得Spring配置文件非常臃肿为此,可以采用自动扫描的形式来配置MyBatis中的映射器——采用MapperScannerConfigurer类同样应该采用Mapper和Java接口相同的规范
MapperScannerConfigurer在Spring的配置属性:
basePackage:指定映射接口文件所在的包路径,当需要扫描多个包时可以使用分号或逗号作为分隔符。指定包路径后,会扫描该包及其子包中的所有文件annotationClass:指定了要扫描的注解名称,只有被注解标识的类才会被配置为映射器sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFactory的Bean名称sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义此属性,则sqlSessionFactoryBeanName将不起作用markerInterface:指定创建映射器的接口
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.edu.ujn.ch10.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
通常情况下,MapperScannerConfigurer在使用时只需通过basePackage属性指定需要扫描的包即可,Spring会自动的通过包中的接口来生成映射器这使得开发人员可以在编写很少代码的情况下,完成对映射器的配置,从而提高开发效率
使用MapperScannerConfigurer进行Mapper文件与接口的装配
DAO层
Customer.java
@Component("customer")
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
+ "]";
}
}
CustomerMapper.java接口
public interface CustomerMapper {
Integer
addOneCustomer(Customer customer
);
Customer
findCustomerByPrimaryKey(Integer id
);
}
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.hlq.ch10.dao.CustomerMapper">
<resultMap id="BaseResultMap" type="Customer">
<id column="id" jdbcType="INTEGER" property="id"></id>
<result column="username" jdbcType="VARCHAR" property="username"></result>
<result column="jobs" jdbcType="VARCHAR" property="jobs"></result>
<result column="phone" jdbcType="VARCHAR" property="phone"></result>
</resultMap>
<sql id="BaseColumnList">
id, username, jobs, phone
</sql>
<select id="findCustomerByPrimaryKey" parameterType="INTEGER" resultMap="BaseResultMap">
SELECT
<include refid="BaseColumnList"></include>
FROM customer
WHERE id = #{id, jdbcType=INTEGER}
</select>
<insert id="addOneCustomer" parameterType="Customer" useGeneratedKeys="true" keyProperty="id">
INSERT INTO customer(username, jobs, phone)
VALUES(#{username, jdbcType=VARCHAR}, #{jobs, jdbcType=VARCHAR}, #{phone, jdbcType=VARCHAR})
</insert>
</mapper>
Service层
接口规范
public interface CustomerService {
int addCustomer(Customer customer
);
Customer
findCustomer(Integer id
);
Integer
insertCustomerTransaction(Customer customer
);
}
实现类
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
@Resource(name
="customerMapper")
private CustomerMapper customerMapper
;
@Override
public int addCustomer(Customer customer
) {
Integer addNum
= customerMapper
.addOneCustomer(customer
);
return addNum
;
}
@Override
public Customer
findCustomer(Integer id
) {
Customer customer
= customerMapper
.findCustomerByPrimaryKey(3);
return customer
;
}
@Override
@Transactional(propagation
=Propagation
.REQUIRED
, isolation
=Isolation
.DEFAULT
, readOnly
=false)
public Integer
insertCustomerTransaction(Customer customer
) {
Integer addNum
= customerMapper
.addOneCustomer(customer
);
int i
= 1/0;
return addNum
;
}
}
SpringJUnit4ClassRunner进行测试
添加注解,声明为SpringTest
@RunWith(SpringJUnit4Runner.clss)@ContextConfiguration(locations=“classpath:spring-mybatis.xml”)
@RunWith(SpringJUnit4ClassRunner
.class)
@ContextConfiguration(locations
="classpath:spring-mybatis.xml")
public class SpringMyBatisTest {
@Autowired
private CustomerService customerService
;
@Autowired
private Customer customer
;
@Autowired
private CustomerMapper customerMapper
;
@Test
public void addOneCustomerTest() {
customer
.setUsername("Hanaaaa");
customer
.setJobs("doctor");
customer
.setPhone("19861823000");
int addNum
= customerService
.addCustomer(customer
);
if (addNum
> 0) {
System
.out
.println("Ok");
} else {
System
.out
.println("fail");
}
}
@Test
public void findCustomerTest() {
Customer icustomer
= customerService
.findCustomer(2);
System
.out
.println(icustomer
);
}
@Test
public void addCustomerTransactionalTest() {
customer
.setUsername("TransactionalTest");
customer
.setJobs("Transaction");
customer
.setPhone("123");
customerService
.insertCustomerTransaction(customer
);
System
.out
.println("获取的id: " + customer
.getId());
}
}
测试结果
Customer [id=2, username=lisi, jobs=student, phone=13964008726]
总结
Spring与MyBatis的整合就是将MyBatis配置到Spring中的Bean,并配置Mapper映射文件使用Mapper类进行操作数据库