Mybatis-spring框架整合开发:
目的:
(1)使用Spring容器用单例模式管理Mybatis的sqlSessionFactory;
(2)使用Spring管理连接池、数据源等;
(3)将dao\mapper动态代理对象注入到Spring容器中,使用时直接获取;
1、Mybatis和Spring框架整合
a)导入所需的包
b)创建Mybatis主配置文件 sqlMapperConfig.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.dunka.bean"/>
</typeAliases>
</configuration>
c) 创建Spring主配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<!-- 读取db.properties文件信息 -->
<context:property-placeholder location="db.properties"/>
<!-- 配置连接池 -->
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置mybatis_spring sqlSessionFactory -->
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 告诉spring mybatis 的核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapperConfig.xml"/>
</bean>
</beans>
主要配置有: 读取数据库位置配置文件db.properties
配置连接池信息
配置mybatis sqlSessionFactory :1、配置数据源 2、告诉spring mybatis的核心配置文件
d)测试配置文档是否正确引用:
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SqlSessionFactoryBean sessionFactoryBean = ac.getBean(SqlSessionFactoryBean.class);
System.out.println(sessionFactoryBean);
}
}
二、DAO式开发:
在上述项目中,
1、添加一个User实体类:
package com.dunka.bean;
import java.util.Date;
/**
* CREATE TABLE `user` (
`u_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`u_username` varchar(64) NOT NULL COMMENT '用户名',
`u_password` varchar(64) DEFAULT NULL COMMENT '用户密码',
`u_sex` varchar(16) DEFAULT NULL COMMENT '用户性别',
`u_createTime` datetime DEFAULT NULL COMMENT '用户创建时间',
`u_cid` int(11) DEFAULT NULL COMMENT '用户国家id',)
*
*/
public class User {
private Integer u_id;
private String u_username;
private String u_password;
private String u_sex;
private Date u_createTime;
private Integer u_cid;
public Integer getU_id() {
return u_id;
}
public void setU_id(Integer u_id) {
this.u_id = u_id;
}
public String getU_username() {
return u_username;
}
public void setU_username(String u_username) {
this.u_username = u_username;
}
public String getU_password() {
return u_password;
}
public void setU_password(String u_password) {
this.u_password = u_password;
}
public String getU_sex() {
return u_sex;
}
public void setU_sex(String u_sex) {
this.u_sex = u_sex;
}
public Date getU_createTime() {
return u_createTime;
}
public void setU_createTime(Date u_createTime) {
this.u_createTime = u_createTime;
}
public Integer getU_cid() {
return u_cid;
}
public void setU_cid(Integer u_cid) {
this.u_cid = u_cid;
}
@Override
public String toString() {
return "User [u_id=" + u_id + ", u_username=" + u_username + ", u_password=" + u_password + ", u_sex=" + u_sex
+ ", u_createTime=" + u_createTime + ", u_cid=" + u_cid + "]";
}
}
2、建立一个UserDao接口和一个UserDaoImpl实现类:
public interface UserDao {
public User getUserById(Integer id);
}
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User getUserById(Integer id) {
SqlSession sqlSession = getSqlSession();
return sqlSession.selectOne("UserMapper.selectUserById",id);
}
}
其中,对比其以前没有使用spring框架时,UserDaoImpl继承了SqlSessionDaoSupport,并且少了SqlSessionFactory的构造类,直接使用了已封装的方法getSqlSession();
3、UserMapper.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="UserMapper">
<!-- 通过用户ID查找用户 -->
<select id="selectUserById" parameterType="Integer" resultType="user">
select * from user where u_id=#{id}
</select>
</mapper>
4、在SqlMapperConfig.xml中添加mapper的映射
<mappers>
<mapper resource="com/dunka/mapper/UserMapper.xml"/>
</mappers>
5、在applicationContext.xml中添加配置sqlSessionFactory,将工厂注入到DAO的父类中
<!-- UserDao 配置 -->
<bean id="userDaoImpl" class="com.dunka.dao.UserDaoImpl">
<!-- 将工厂注入到DAO的父类 sqlSessionFactory -->
<property name="sqlSessionFactory" ref="SqlSessionFactoryBean"/>
</bean>
6、测试类
public class UserDaoTest {
@Test
public void UserDaoTest1() {
ApplicationContext aContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDaoImpl userDaoImpl = aContext.getBean(UserDaoImpl.class);
User user = userDaoImpl.getUserById(2);
System.out.println(user);
}
}
与普通DAO式开发最大的不同,便是少了对于SqlSessionFactory的配置,直接交由spring处理。
三、Mapper的动态代理开发
在第二的基础上,进一步改写代码:
1、添加UserMapper的接口,其中的方法名对应着UserMapper.xml的id
public interface UserMapper {
public User selectUserById(Integer id);
}
2、在SqlMapperConfig.xml中添加mapper的映射,改为扫描包
<mappers>
<package name="com.dunka.mapper"/>
</mappers>
3、在applicationContext.xml中添加Mapper动态代理开发:共两步:一是注入sqlSessionFactory 二是配置接口
<!-- Mapper 动态代理开发 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactory" ref="SqlSessionFactoryBean"/>
<!-- 配置接口 -->
<property name="mapperInterface" value="com.dunka.mapper.UserMapper"/>
</bean>
4、测试类
public class UserMapperTest {
@Test
public void UserDaoTest1() {
ApplicationContext aContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//其中的userMapper对应的是applicationContext文件的Mapper动态代理开发配置的<bean id=“userMapper”>
//UserMapper mapper = (UserMapper) aContext.getBean("userMapper");
UserMapper mapper = aContext.getBean(UserMapper.class);
User user = mapper.selectUserById(3);
System.out.println(user);
}
}
总结:最主要就是spring帮助我们动态生成sqlSesionFactory并且能够自动生成Mapper的实现类。
对比一下仅使用Mybatis的测试类就能清楚:帮助我们省略了以下几个步骤:
String resource = "SqlMapperConfig.xml";
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().
build(Resources.getResourceAsStream(resource));
SqlSession sqlSession = ssf.openSession();
UserMapper uMapper = sqlSession.getMapper(UserMapper.class);
四、Mapper扫描开发:避免后期开发时需要编写多个接口,直接在mapper包里扫描所有mapper,自动生成。也不需要添加sqlSessionFactory的配置。
1、在三的基础上,只需改变一个地方,就是applicationContext.xml的添加一个动态扫描配置
<!-- Mapper 动态扫描开发 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dunka.mapper"/>
</bean>
其中,basePackage不要更改名字,如果有eclipse的spring插件,按住alt+/就会有提示
2、利用前面的测试类进行测试即可。