Spring(7):Mybatis 与 Spring 整合小结与实例分析(上)

2017/12/28

Spring和Mybatis的核心是什么?

      Spring的核心:IOC和AOP;单干的时候,就新建了一个applicationContext.xml,然后添加各种各样的Bean,与之对应的必要的实体类;的的确确省事省心,避免了大量冗余代码;

      Mybatis的核心:SQL与实体对象的映射;单干的时候,就新建了一个mybatis-config.xml作全局配置,mapper.xml作sql映射配置,然后添加各个实体类和相关的操作接口,的的确确方便,避免一次次的jdbc连接断开;


那么要如何将两者结合到一起呢,它们之间的依赖关系是什么?

回答:

(1)spring的ioc机制,可以接管组件创建工作和依赖管理,所以“整合”主要工作就是把Mybatis框架涉及的核心组件配置到Spring容器里;

(2)Spring是老大,Mybatis是手下;业务逻辑对象依赖基于Mybatis技术实现的DAO对象,核心是获取SQLSession实例。在此之前还有依赖SQLSessionFactory实例。在此之前需要依赖SQLSessionFactoryBuilder从数据源、SQL映射文件等信息构建。

       随着引入Spring框架,以上流程将全部移交给Spring,发挥Spring框架Bean容器的作用,接管创建工作和管理组件生命周期,对组件之间的依赖关系进行解耦合管理。


下面是Spring框架对Mybatis框架的一个整合示例,主要方便各位捋顺思路,抛砖引玉。


【1】导入所需的 jar 包


图1


开发文件框架:


图2



【2】建立开发目录,创建实体类User.java:

package com.smbms.pojo;

import java.util.Date;
import java.util.List;

public class User implements java.io.Serializable{
	private Integer id;
	private String userCode;
	private String userName;
	private String userPassword;
	private Integer gender;
	private Date birthday;
	private String phone;
	private String address ;
	private Integer userRole;
	private Integer createdBy;
	private Date creationDate;
	private Integer modifyBy;
	private Date modifyDate;
	private String userRoleName;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	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 getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	public String getUserRoleName() {
		return userRoleName;
	}
	public void setUserRoleName(String userRoleName) {
		this.userRoleName = userRoleName;
	}
	public User() {
		super();
		// TODO 自动生成的构造函数存根
	}
	
}

【3】创建实体类User的DAO接口UserMapper.java:

package com.smbms.pojo;

import java.util.List;

import com.smbms.pojo.User;

public interface UserMapper {

	/**
	 * 下面定义的方法是用于--Mybatis/Spring整合练习。
	 * */
	public List<User> getUserList(User user);
}

【4】新建UserMapper.java文件,配置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="com.smbms.pojo.UserMapper">
	<!-- 下面定义的映射语句是用于Mybatis/Spring整合练习。 -->
	<resultMap type="com.smbms.pojo.User" id="userlist">
		<result property="userRoleName" column="roleName"/>
	</resultMap>
	<select id="getUserList" parameterType="com.smbms.pojo.User" resultMap="userlist">
		select u.* ,r.roleName from smbms_user u ,smbms_role r
		where u.userName like CONCAT('%',#{userName},'%')
		and u.userRole = #{userRole} and u.userRole = r.id
	</select>	
 </mapper>


【5】新建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.smbms.pojo"/>
 	</typeAliases> 
 </configuration>


【6】实现Spring对Mybatis的整合--

             6.1 配置数据源,添加两个jar包(commons-logging-1.0.4.jar + commons-dbcp-1.4.jar),新建applicationContext-mybatis.xml 配置文件 ;

在 applicationContext-mybatis.xml 进行数据源配置代码:

	<!-- 数据源配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
	     destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url">
		<value><![CDATA[jdbc:mysql://127.0.0.1:3306/test?
				useUnicode=true&characterEncoding=utf-8]]></value>
	</property>
	<property name="username" value="root"></property>
	<property name="password" value=""></property>    
    </bean>



             6.2 配置SqlSessionFactoryBean;

在 applicationContext-mybatis.xml 进行SqlSessionFactoryBean配置代码:

    <!-- SqlSessionFactoryBean 配置 -->
    <bean id="sqlSessionFactory"
    		class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 引用数据源组件 -->
		<property name="dataSource" ref="dataSource"></property>
	<!-- 引用Mybatis配置文件的配置 -->
		<property name="configLocation" 
		        value="classpath:mybatis-config.xml"></property>
	<!-- 配置SQL映射文件信息 ,逐个列出SQL映射文件麻烦,所以使用 mapperLocations 属性扫描加载SQL映射文件-->
	    <property name="mapperLocations">
	    	<list>
	    		<value>classpath:com/smbms/pojo/**/*.xml</value>
	    	</list>
	    </property>
    </bean>



             6.3 配置SqlSessionTemplate:

Mybatis-Spring整合包提供了SQLSessionTemplate类,实现了Mybatis的SQLSession接口,可以替换Mybatis原有的SQLSession实现类,提供数据库访问操作。所以,配置SqlSessionTemplate,并在UserMapper实现类中使用的代码;

新建UserMapperImpl.java文件

package com.smbms.pojo;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.smbms.pojo.User;

public class UserMapperImpl implements UserMapper{
	private SqlSessionTemplate sqlSession;
	
	@Override
	public List<User> getUserList(User user) {
		return sqlSession.selectList("com.smbms.pojo.UserMapper.getUserList",user);
	}

	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}

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

	
	public UserMapperImpl() {
		super();
		// TODO 自动生成的构造函数存根
	}

	public UserMapperImpl(SqlSessionTemplate sqlSession) {
		super();
		this.sqlSession = sqlSession;
	}
	
	
}

在 applicationContext-mybatis.xml 进行SqlSessionTemplate配置代码:

    
    <!-- 配置SQLSessionTemplate -->
   	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
   		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
   	</bean>
   	<!-- 配置DAO组件并进入SQLSessionTemplate实例 -->
   	<bean id="userMapper" class="com.smbms.pojo.UserMapperImpl">
   		<constructor-arg name="sqlSession" ref="sqlSessionTemplate"></constructor-arg>
   	</bean>


【7】至此,配置工作大致完成,下面是业务文件的编写:

新建业务接口 UserService.java:

package com.smbms.pojo;

import java.util.List;

public interface UserService {
	public List<User> findUsersWithConditions(User user);
}

新建业务接口实现类 UserServiceImpl.java:

package com.smbms.pojo;

import java.util.List;

public class UserServiceImpl implements UserService{
	private UserMapper userMapper;

	@Override
	public List<User> findUsersWithConditions(User user) {
		try{
			return userMapper.getUserList(user);
		}catch(RuntimeException e){
			e.printStackTrace();
			throw e;
		}
	}

	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}
	
	
}

applicationContext-mybatis.xml 对业务类编写bean配置:

   	<!-- 配置业务Bean并注入DAO实例 -->
   	<bean id="userService" class="com.smbms.pojo.UserServiceImpl">
   		<property name="userMapper" ref="userMapper"></property>
   	</bean>

【8】applicationContext-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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
	
	<!-- 数据源配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
	     destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url">
		<value><![CDATA[jdbc:mysql://127.0.0.1:3306/test?
				useUnicode=true&characterEncoding=utf-8]]></value>
	</property>
	<property name="username" value="root"></property>
	<property name="password" value=""></property>    
    </bean>
    
    <!-- SqlSessionFactoryBean 配置 -->
    <bean id="sqlSessionFactory"
    		class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 引用数据源组件 -->
		<property name="dataSource" ref="dataSource"></property>
	<!-- 引用Mybatis配置文件的配置 -->
		<property name="configLocation" 
		        value="classpath:mybatis-config.xml"></property>
	<!-- 配置SQL映射文件信息 ,逐个列出SQL映射文件麻烦,所以使用 mapperLocations 属性扫描加载SQL映射文件-->
	    <property name="mapperLocations">
	    	<list>
	    		<value>classpath:com/smbms/pojo/**/*.xml</value>
	    	</list>
	    </property>
    </bean>
    
    <!-- 配置SQLSessionTemplate -->
   	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
   		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
   	</bean>
   	<!-- 配置DAO组件并进入SQLSessionTemplate实例 -->
   	<bean id="userMapper" class="com.smbms.pojo.UserMapperImpl">
   		<constructor-arg name="sqlSession" ref="sqlSessionTemplate"></constructor-arg>
   	</bean>
	
   	<!-- 配置业务Bean并注入DAO实例 -->
   	<bean id="userService" class="com.smbms.pojo.UserServiceImpl">
   		<property name="userMapper" ref="userMapper"></property>
   	</bean>
    
</beans>



【9】编写测试类 UserServiceImpTest.java(调用业务类的方法):


package com.smbms.pojo;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserServiceImpTest {

	@SuppressWarnings("resource")
	@Test
	public void test() {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
		UserService userService = (UserService)ctx.getBean("userService");
		User userCondition = new User();
		userCondition.setUserName("mmb");
		userCondition.setUserRole(110);

		List<User> userList = new ArrayList<User>();
		userList = userService.findUsersWithConditions(userCondition);

		for(User userResult:userList){
			System.out.println("testGetUserList userCode:"+userResult.getUserCode()+
					"userName: "+userResult.getUserName()+
					"userRole: "+userResult.getUserRole()+
					"userRoleName: "+userResult.getUserRoleName()+
					"userAddress: "+userResult.getCreationDate());
		}
	}

}


【10】输出结果:

testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null
testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null
testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null
testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null
testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null

综上,以上是Spring对Mybatis的整合实例。注意特征:我们将Mapper接口实现了,然后调用方法才能访问数据库,是因为在实现类中有SqlSessionTemplate的存在。但是,之后我会总结另一个方法,将不用把接口实现,就能访问数据库,这也是Spring框架带来的好处。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后台技术汇

对你的帮助,是对我的最好鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值