基本整合方式
Spring框架整合其他框架的本质其实就是把其他框架交给Spring框架管理。Spring框架通过IOC、AOP等机制实现与其他框架的连接,最终建立一个低耦合的应用架构,这大大增强了系统的灵活性,便于功能扩展。
整合思路梳理
MyBatis框架主要是通过SqlSession实例实现对数据的操作,而SqlSession实例是通过SqlSessionFactory创建的,SqlSessionFactory实例又是由SqlSessionFactoryBuilder依据MyBatis配置文件中的数据源、SQL映射文件等信息构建的。
Spring框架整合MyBatis框架的主要流程包括添加依赖jar包、编写MyBatis配置文件及在Spring框架配置文件中做整合配置三个方面的操作。
整合所需的依赖及配置
maven依赖
<!-- dbcp连接池及其依赖 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
首先我们先完成MyBatis框架配置、实体类、映射接口以及映射文件
示例代码
实体类
public class SysUser implements Serializable {
private static final long serialVersionUID = 42L;
private Integer id; // id
private String account; // 用户编码
private String realName; // 用户名称
private String password; // 用户密码
private Integer sex; // 性别
private Date birthday; // 出生日期
private String phone; // 电话
private String address; // 地址
private Integer roleId; // 用户角色ID
private Integer createdUserId; // 创建者
private Date createdTime; // 创建时间
private Integer updatedUserId; // 更新者
private Date updatedTime; // 更新时间
private Integer age; // 年龄
private String roleName; // 角色名称
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getCreatedUserId() {
return createdUserId;
}
public void setCreatedUserId(Integer createdUserId) {
this.createdUserId = createdUserId;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Integer getUpdatedUserId() {
return updatedUserId;
}
public void setUpdatedUserId(Integer updatedUserId) {
this.updatedUserId = updatedUserId;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
映射接口
public interface SysUserMapper {
List<SysUser> selectSysUserList(SysUser sysUser);
/**
* 保存用户
* @param sysUser
* @return
*/
public int add(SysUser sysUser);
}
SQL映射文件
<?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="dao.sysUser.SysUserMapper">
<!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 -->
<resultMap id="SysUserResult" type="SysUser">
<result property="roleName" column="roleName"/>
</resultMap>
<select id="selectSysUserList" parameterType="SysUser" resultMap="SysUserResult">
select u.*,r.roleName from t_sys_user u,t_sys_role r
where u.roleId = r.id
and u.roleId = #{roleId}
and u.realName like concat('%',#{realName},'%')
</select>
<insert id="add" parameterType="SysUser">
insert into t_sys_user (account,realName,password,sex,birthday,phone,address,roleId,createdUserId,createdTime)
values (#{account},#{realName},#{password},#{sex},#{birthday},#{phone},#{address},#{roleId},#{createdUserId},#{createdTime})
</insert>
</mapper>
MyBatis核心配置文件
<?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>
<!-- 设置MyBatis框架的运行时行为 -->
<settings>
<!-- 使用Log4j作为MyBatis框架的日志实现 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="pojo"/>
</typeAliases>
</configuration>
使用Spring配置文件配置数据源
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/cvs_db?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="cuishujian"/>
</bean>
通过Spring配置文件创建SqlSessionFactory
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource"/>
<!-- 引用MyBatis配置文件中的配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 配置SQL映射文件信息 -->
<property name="mapperLocations">
<list>
<value>classpath:mapper/*.xml</value>
</list>
</property>
</bean>
通过SqlSessionTemplate操作数据库
public class SysUserMapperImpl implements SysUserMapper {
private SqlSessionTemplate sqlSession;
@Override
public List<SysUser> selectSysUserList(SysUser sysUser) {
return sqlSession.selectList("dao.sysUser.SysUserMapper.selectSysUserList",sysUser);
}
/**
* 保存用户
*
* @param sysUser
* @return
*/
@Override
public int add(SysUser sysUser) {
return sqlSession.insert("dao.sysUser.SysUserMapper.add",sysUser);
}
public SqlSessionTemplate getSqlSession(){
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession){
this.sqlSession = sqlSession;
}
}
通过Spring配置文件对SqlSessionTemplate进行注入,配置文件如下
<!-- 配置SqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
编写相关业务代码以及Spring配置文件中的配置信息
SysUserService类中的关键代码
public interface SysUserService {
List<SysUser> getList(SysUser sysUser);
/**
* 保存用户
* @param sysUser
* @return
*/
public boolean add(SysUser sysUser);
}
SysUserServiceImpl类中的关键代码
public class SysUserServiceImpl implements SysUserService {
private SysUserMapper sysUserMapper;
@Override
public List<SysUser> getList(SysUser sysUser) {
try {
return sysUserMapper.selectSysUserList(sysUser);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
/**
* 保存用户
*
* @param sysUser
* @return
*/
@Override
public boolean add(SysUser sysUser) {
boolean result = false;
try {
if (sysUserMapper.add(sysUser) == 1){
result = true;
// 测试事务回滚时,打开注释
throw new RuntimeException();
}
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
return result;
}
public SysUserMapper getSysUserMapper() {
return sysUserMapper;
}
public void setSysUserMapper(SysUserMapper sysUserMapper) {
this.sysUserMapper = sysUserMapper;
}
}
Spring配置文件中关键代码
<!-- 配置业务Bean -->
<bean id="sysUserService" class="service.impl.SysUserServiceImpl">
<property name="sysUserMapper" ref="sysUserMapper"/>
</bean>
通过以上配置讲SysUserMapper注入SysUserService中。编写测试代码
public class SysUserTest {
private Logger logger = LogManager.getLogger(SysUserTest.class);
@Before
public void setUp() throws Exception{}
@Test
public void testGetUserList(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SysUserService userService = (SysUserService) ctx.getBean("sysUserService");
List<SysUser> userList = new ArrayList<SysUser>();
SysUser userCondition = new SysUser();
userCondition.setRealName("赵");
userCondition.setRoleId(2);
userList = userService.getList(userCondition);
for (SysUser userResult : userList) {
logger.debug("testGetUserList account:"
+ userResult.getAccount() + " and realName:"
+ userResult.getRealName() + " and roleId:"
+ userResult.getRoleId() + " and roleName:"
+ userResult.getRoleName() + " and address:"
+ userResult.getAddress()
);
}
}
@Test
public void testAddUser() throws ParseException{
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SysUserService userService = (SysUserService) ctx.getBean("sysUserService");
SysUser user = new SysUser();
user.setAccount("test002");
user.setRealName("测试用户002");
user.setPassword("1234567");
Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse("2003-10-22");
user.setBirthday(birthday);
user.setAddress("测试地址abc");
user.setSex(1);
user.setPhone("13411110000");
user.setRoleId(1);
user.setCreatedUserId(1);
user.setCreatedTime(new Date());
boolean result = userService.add(user);
logger.debug("testAdd result:" + result);
}
}
使用SqlSesssionDaoSupport简化编码
SysUserMapperImpl类中的关键代码
public class SysUserMapperImpl extends SqlSessionDaoSupport implements SysUserMapper {
@Override
public List<SysUser> selectSysUserList(SysUser sysUser) {
this.getSqlSession().selectList("dao.sysUser.SysUserMapper.selectSysUserList",sysUser);
}
/**
* 保存用户
*
* @param sysUser
* @return
*/
@Override
public int add(SysUser sysUser) {
return this.getSqlSession().insert("dao.sysUser.SysUserMapper.add",sysUser);
}
}
Spring配置文件中的关键代码
<bean id="sysUserMapper" class="dao.sysUser.impl.SysUserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
SqlSessionDaoSupport类中提供了setSqlSessionFactory()方法用来注入SqlSessionFactory并创建SqlSessionTemplate实例,同时还提供getSqlSession()方法将创建好的SqlSessionTemplate实例返回。这样Dao实现类只需要继承SqlSessionDaoSupport类即可通过getSqlSession()方法活得创建好的SqlSessionTemplate实例,无需额外定义SqlSession属性和setter方法。而Spring配置文件也无需再配置SqlSessionTemplate,只需要通过该Dao对象的setSqlSessionFactory()方法为其注入SqlSessionFactory即可,这一定程度上进一步简化了Dao组件的开发工作。
映射器整合方式
在实例代码中SysUserMapperImpl中主要使用SqlSessionTemplate类实现Dao层的相关操作。但是这种方式不仅需要编写Mapper接口的实现类,还需要使用字符串定义方法的位置,这样不仅代码繁多,还容易出错、不易维护,如果命名空间发生变化,改起来会很麻烦。
在MyBatis中可以使用SqlSession的getMapper(Class<T>type)方法,根据指定的映射器和映射文件直接生成实现类,大大减少工作量。SqlSessionTemplate类实现了SqlSession接口,所以,其也具备同样的功能,且利用MyBatis-Spring提供的组件可以通过配置的方式直接为业务对象注入映射器实现类,无需额外的编码,对于不包含其他非MyBatis框架工作的数据访问操作,这是首选的做法。
使用MapperFactoryBean注入映射器
Spring配置文件
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource"/>
<!-- 引用MyBatis配置文件中的配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 配置SQL映射文件信息 -->
<!-- <property name="mapperLocations">-->
<!-- <list>-->
<!-- <value>classpath:mapper/*.xml</value>-->
<!-- </list>-->
<!-- </property>-->
</bean>
<bean id="sysUserMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="dao.sysUser.SysUserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
使用MapperScannerConfigurer注入映射器
Spring配置文件
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource"/>
<!-- 引用MyBatis配置文件中的配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao"/>
</bean>