Spring整合MyBatis
博客分类:
OpenSource--Spring
Spring整合MyBatisMyBatis分页SqlSessionTemplate和SqlSessionDaoSupport
首先介绍一下整合中用到的几个类
1)org.mybatis.spring.SqlSessionTemplate
SqlSessionTemplate是Mybatis-Spring的核心,这个类实现了Mybatis的SqlSession接口,调用Mybatis的方法进行相关操作。SqlSessionTemplate是线程安全的,可以被多个DAO所共享所用,它被用来替代默认的MyBatis实现的DefaultSqlSession,DefaultSqlSession不能参与到Spring的事务中也不能被注入因为它是线程不安全的。
2)org.mybatis.spring.support.SqlSessionDaoSupport
SqlSessionDaoSupport是一个抽象的支持类,用来提供SqlSession。通过调用getSqlSession()方法得到SqlSessionTemplate对象。SqlSessionDaoSupport需要一个sqlSessionFactory或sqlSessionTemplate属性来设置,这些被明确地设置或由Spring来自动装配。如果两者都被设置了,那么sqlSessionFactory将被忽略。
下面将全程演示Spring和Mybatis的整合。在网上看到有几种方式的实现,其实都没有多大的区别,一种是直接在DAO中手动注入SqlSessionTemplate,另一种是继承SqlSessionDaoSupport让它帮助我们自动注入在Spring配置文件中配置的SqlSessionTemplateBean。笔者还是建议采用继承方式实现。废话不多说,开始吧
源码下载地址(包括所需jar包,可直接运行):
http://download.csdn.net/detail/u011631266/7348671
1.导包
除了Spring需要的包外(如果你还不知道需要那些,就全部导进去吧),还需要导入:
c3p0-0.9.1.2.jar
commons-collections-3.2.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-pool-1.4.jar
mybatis-3.1.1.jar
mybatis-spring-1.1.1.jar
mysql-connector-java-5.1.18-bin.jar
2.添加配置文件
1)Spring配置文件(src/config/applicationContext.xml)
Java代码收藏代码
<?xmlversion="1.0"encoding="utf-8"?>
<beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName"default-lazy-init="false">
<context:property-placeholderlocation="classpath:config/important.properties"/>
<context:component-scanbase-package="com.jiang"/>
<context:annotation-config/>
<beanid="sampleDataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<propertyname="driverClass">
<value>${db.driverClassName}</value>
</property>
<propertyname="jdbcUrl">
<value>${db.url}</value>
</property>
<propertyname="user">
<value>${db.username}</value>
</property>
<propertyname="password">
<value>${db.password}</value>
</property>
<propertyname="initialPoolSize">
<value>${db.initialPoolSize}</value>
</property>
<propertyname="minPoolSize">
<value>${db.minPoolSize}</value>
</property>
<propertyname="maxPoolSize">
<value>${db.maxPoolSize}</value>
</property>
<propertyname="maxIdleTime">
<value>${db.maxIdleTime}</value>
</property>
<propertyname="acquireIncrement">
<value>${db.acquireIncrement}</value>
</property>
<propertyname="acquireRetryAttempts">
<value>${db.acquireRetryAttempts}</value>
</property>
<propertyname="acquireRetryDelay">
<value>${db.acquireRetryDelay}</value>
</property>
<propertyname="maxStatements">
<value>${db.maxStatements}</value>
</property>
<propertyname="maxStatementsPerConnection">
<value>${db.maxStatementsPerConnection}</value>
</property>
<propertyname="checkoutTimeout">
<value>${db.checkoutTimeout}</value>
</property>
<propertyname="breakAfterAcquireFailure">
<value>${db.breakAfterAcquireFailure}</value>
</property>
</bean>
<beanid="sampleSqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="sampleDataSource"/>
<propertyname="configLocation"value="config/Configuration.xml"/>
</bean>
<beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-argref="sampleSqlSessionFactory"/>
</bean>
</beans>
2)MyBatis主配置文件(src/config/Configuration.xml)
Java代码收藏代码
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapperresource="com/jiang/dao/mapper/User.xml"/>
</mappers>
</configuration>
3)数据源配置属性(src/important.properties)
Java代码收藏代码
db.transaction.attributes=PROPAGATION_REQUIRED,-Exception
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/mybatis
db.username=root
db.password=1234
db.initialPoolSize=5
db.minPoolSize=2
db.maxPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=3
db.acquireRetryAttempts=30
db.acquireRetryDelay=2000
db.maxStatements=10
db.maxStatementsPerConnection=10
db.checkoutTimeout=0
db.breakAfterAcquireFailure=false
3.添加实体(src/com/jiang/entity/User.java)
Java代码收藏代码
packagecom.jiang.entity;
publicclassUser{
privateLongid;
privateStringuserName;
privateintuserAge;
privateStringuserAddress;
publicLonggetId(){
returnid;
}
publicvoidsetId(Longid){
this.id=id;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicintgetUserAge(){
returnuserAge;
}
publicvoidsetUserAge(intuserAge){
this.userAge=userAge;
}
publicStringgetUserAddress(){
returnuserAddress;
}
publicvoidsetUserAddress(StringuserAddress){
this.userAddress=userAddress;
}
}
4.DAO
1)接口(src/com/jiang/dao/ISuperDAO.java)
Java代码收藏代码
packagecom.jiang.dao;
importjava.util.List;
importjava.util.Map;
importcom.jiang.common.BasePageDTO;
importcom.jiang.common.Pagination;
importcom.jiang.entity.User;
publicinterfaceISuperDAO{
publicLonginsert(StringstatementName,UserparameterObject);
publicIntegerupdate(StringstatementName,ObjectparameterObject);
publicIntegerdelete(StringstatementName,ObjectparameterObject);
public<T>TgetObject(StringstatementName,ObjectparameterObject);
public<T>List<T>getList(StringstatementName,ObjectparameterObject);
public<T,V>Map<T,V>getMap(StringstatementName,ObjectparameterObject,Stringkey);
publicPaginationqueryPagination(StringstatementName,BasePageDTObaseParamDto);
}
2)实现(src/com/jiang/dao/SuperDAO.java)
Java代码收藏代码
packagecom.jiang.dao;
importjava.util.List;
importjava.util.Map;
importorg.mybatis.spring.support.SqlSessionDaoSupport;
importorg.springframework.dao.DataAccessException;
importorg.springframework.stereotype.Repository;
importcom.jiang.common.BasePageDTO;
importcom.jiang.common.Pagination;
importcom.jiang.entity.User;
@Repository
publicclassSuperDAOextendsSqlSessionDaoSupportimplementsISuperDAO{
@Override
publicLonginsert(StringstatementName,UserparameterObject){
this.getSqlSession().insert(statementName,parameterObject);
return(long)parameterObject.getId();
}
@Override
publicIntegerupdate(StringstatementName,ObjectparameterObject){
returnthis.getSqlSession().update(statementName,parameterObject);
}
@Override
publicIntegerdelete(StringstatementName,ObjectparameterObject){
returnthis.getSqlSession().delete(statementName,parameterObject);
}
@Override
public<T>TgetObject(StringstatementName,ObjectparameterObject){
return(T)this.getSqlSession().selectOne(statementName,parameterObject);
}
@Override
public<T>List<T>getList(StringstatementName,ObjectparameterObject)throwsDataAccessException{
returnthis.getSqlSession().selectList(statementName,parameterObject);
}
@Override
public<T,V>Map<T,V>getMap(StringstatementName,ObjectparameterObject,Stringkey){
returnthis.getSqlSession().selectMap(statementName,parameterObject,key);
}
@Override
publicPaginationqueryPagination(StringstatementName,BasePageDTObaseParamDTO){
if(baseParamDTO==null){
returnnull;
}
if(baseParamDTO.getPageNum()==null||baseParamDTO.getPageNum().intValue()<1){
baseParamDTO.setPageNum(Pagination.DEFAULT_PAGE_NUM);
}
if(baseParamDTO.getPageSize()==null||baseParamDTO.getPageSize().intValue()<1){
baseParamDTO.setPageSize(Pagination.DEFAULT_PAGE_SIZE);
}
//计算记录起始值和结束值
baseParamDTO.setEndIdx(baseParamDTO.getPageSize()*baseParamDTO.getPageNum());
baseParamDTO.setStartIdx(baseParamDTO.getPageSize()*(baseParamDTO.getPageNum()-1));
IntegertotalCount=(Integer)this.getSqlSession().selectOne(statementName+"-count",baseParamDTO);
ListresultList=this.getSqlSession().selectList(statementName,baseParamDTO);
returnnewPagination(baseParamDTO.getPageSize(),baseParamDTO.getPageNum(),totalCount,resultList);
}
}
5.Mapper(src/com/jiang/dao/mapper/User.java)
Java代码收藏代码
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="UserEntityMapper">
<resultMaptype="com.jiang.entity.User"id="BaseResultMap">
<idcolumn="id"property="id"/>
<resultcolumn="user_name"property="userName"/>
<resultcolumn="user_age"property="userAge"/>
<resultcolumn="user_address"property="userAddress"/>
</resultMap>
<sqlid="Base_Column_List">
id,user_name,user_age,user_address
</sql>
<sqlid="paginationSuffix">
limit#{startIdx,jdbcType=DECIMAL},#{pageSize,jdbcType=DECIMAL}
</sql>
<!--注意:Oracle返回ID要用SELECTLOGS_SEQ.nextvalASIDFROMDUAL-->
<insertid="insertUser"parameterType="com.jiang.entity.User">
<selectKeyresultType="java.lang.Long"order="AFTER"keyProperty="id">
SELECTLAST_INSERT_ID()ASid
</selectKey>
insertintouser(
user_name
<iftest="userAge!=null">
,user_age
</if>
,user_address
)
values(
#{userName,jdbcType=VARCHAR}
<iftest="userAge!=null">
,#{userAge,jdbcType=VARCHAR}
</if>
,#{userAddress,jdbcType=VARCHAR}
)
</insert>
<updateid="updateUser"parameterType="com.jiang.entity.User">
updateuser
set
user_address=#{userAddress,jdbcType=VARCHAR}
where
id=#{id,jdbcType=VARCHAR}
<![CDATA[anduser_age<10]]>
</update>
<deleteid="deleteUser"parameterType="int">
deletefromuserwhereid=#{id}
</delete>
<selectid="getUserByID"parameterType="int"resultMap="BaseResultMap">
select<includerefid="Base_Column_List"/>
fromuserwhereid=#{id}
</select>
<selectid="getUserList"parameterType="com.jiang.entity.User"resultMap="BaseResultMap">
select<includerefid="Base_Column_List"/>
fromuserwhereuser_age>#{userAge,jdbcType=VARCHAR}
</select>
<selectid="getPageUser"parameterType="com.jiang.common.UserParamDTO"resultMap="BaseResultMap">
select<includerefid="Base_Column_List"/>
fromuserwhereuser_address=#{userAddress,jdbcType=VARCHAR}
<includerefid="paginationSuffix"/>
</select>
<selectid="getPageUser-count"parameterType="com.jiang.common.UserParamDTO"resultType="java.lang.Integer">
selectcount(1)
fromuserwhereuser_address=#{userAddress,jdbcType=VARCHAR}
</select>
</mapper>
6.工具类(分页需要用到)
1)分页基类(src/com/jiang/common/BasePageDTO.java)
Java代码收藏代码
packagecom.jiang.common;
importjava.io.Serializable;
importjava.util.Date;
/**
*分页查询基本传入参数
*/
publicclassBasePageDTOimplementsSerializable{
privatestaticfinallongserialVersionUID=-3378378237423457439L;
privateDatebegin;
privateDateend;
/**
*分页使用的参数,分页大小
*/
privateIntegerpageSize;
/**
*分页使用的参数,当前分页号
*/
privateIntegerpageNum;
/**
*查询记录开始行号
*/
privateIntegerstartIdx;
/**
*查询记录结束行号
*/
privateIntegerendIdx;
publicIntegergetPageSize(){
returnpageSize;
}
publicvoidsetPageSize(IntegerpageSize){
this.pageSize=pageSize;
}
publicIntegergetPageNum(){
returnpageNum;
}
publicvoidsetPageNum(IntegerpageNum){
this.pageNum=pageNum;
}
publicIntegergetStartIdx(){
returnstartIdx;
}
publicvoidsetStartIdx(IntegerstartIdx){
this.startIdx=startIdx;
}
publicIntegergetEndIdx(){
returnendIdx;
}
publicvoidsetEndIdx(IntegerendIdx){
this.endIdx=endIdx;
}
publicDategetBegin(){
returnbegin;
}
publicvoidsetBegin(Datebegin){
this.begin=begin;
}
publicDategetEnd(){
returnend;
}
publicvoidsetEnd(Dateend){
this.end=end;
}
}
2)User分页DTO(src/com/jiang/common/UserParamDTO.java)
Java代码收藏代码
packagecom.jiang.common;
publicclassUserParamDTOextendsBasePageDTO{
privatestaticfinallongserialVersionUID=5281918320758904576L;
privateStringuserAddress;
publicStringgetUserAddress(){
returnuserAddress;
}
publicvoidsetUserAddress(StringuserAddress){
this.userAddress=userAddress;
}
}
3)分页返回对象(src/com/jiang/common/Pagination.java)
Java代码收藏代码
packagecom.jiang.common;
importjava.io.Serializable;
importjava.util.List;
importorg.apache.commons.lang3.builder.ToStringBuilder;
/**
*分页
*/
publicclassPagination<P>implementsSerializable{
privatestaticfinallongserialVersionUID=1L;
/**
*默认分页大小
*/
publicstaticfinalintDEFAULT_PAGE_SIZE=20;
/**
*默认页码
*/
publicstaticfinalintDEFAULT_PAGE_NUM=1;
/**
*分页使用的参数,分页大小
*/
privateintpageSize;
/**
*分页使用的参数,当前分页号
*/
privateintpageNum;
/**
*分页使用的参数,总数据条数
*/
privateinttotalCount;
/**
*分页使用的参数,总页数
*/
privateintpageCount;
/**
*查询结果数据
*/
privateList<P>datas=null;
publicPagination(intpageSize,intpageNum,inttotalCount,List<P>datas){
this.pageSize=pageSize;
this.pageNum=pageNum;
this.totalCount=totalCount;
this.datas=datas;
if(this.pageSize==0){
pageCount=0;
}elseif(this.totalCount%this.pageSize==0){
pageCount=this.totalCount/this.pageSize;
}else{
pageCount=totalCount/this.pageSize+1;
}
}
publicintgetPageSize(){
returnpageSize;
}
publicintgetPageNum(){
returnpageNum;
}
publicintgetTotalCount(){
returntotalCount;
}
publicintgetPageCount(){
returnthis.pageCount;
}
publicList<P>getDatas(){
returndatas;
}
@Override
publicStringtoString(){
returnToStringBuilder.reflectionToString(this);
}
}
7.Service
1)接口(src/com/jiang/service/UserService.java)
Java代码收藏代码
packagecom.jiang.service;
importjava.util.List;
importcom.jiang.common.Pagination;
importcom.jiang.common.UserParamDTO;
importcom.jiang.entity.User;
publicinterfaceUserService{
publicLonginsertUser(Useruser);
publicIntegerupdateUser(Useruser);
publicIntegerdeleteUser(Longid);
publicUsergetUserById(Longid);
publicList<User>getUserList(Useruser);
publicPagination<User>getPageUser(UserParamDTOuserParamDTO);
}
2)实现(src/com/jiang/service/impl/UserServiceImpl.java)
Java代码收藏代码
packagecom.jiang.service.impl;
importjava.util.List;
importjavax.annotation.Resource;
importorg.springframework.stereotype.Component;
importcom.jiang.common.Pagination;
importcom.jiang.common.UserParamDTO;
importcom.jiang.dao.ISuperDAO;
importcom.jiang.entity.User;
importcom.jiang.service.UserService;
@Component("userService")
publicclassUserServiceImplimplementsUserService{
@Resource
privateISuperDAOsuperDAO;
@Override
publicLonginsertUser(Useruser){
returnsuperDAO.insert("UserEntityMapper.insertUser",user);
}
@Override
publicIntegerupdateUser(Useruser){
returnsuperDAO.update("UserEntityMapper.updateUser",user);
}
@Override
publicIntegerdeleteUser(Longid){
returnsuperDAO.delete("UserEntityMapper.deleteUser",id);
}
@Override
publicUsergetUserById(Longid){
returnsuperDAO.getObject("UserEntityMapper.getUserByID",id);
}
@Override
publicList<User>getUserList(Useruser){
returnsuperDAO.getList("UserEntityMapper.getUserList",user);
}
@Override
publicPagination<User>getPageUser(UserParamDTOuserParamDTO){
returnsuperDAO.queryPagination("UserEntityMapper.getPageUser",userParamDTO);
}
}
8.测试类(src/test/MybatisSpringTest.java)
Java代码收藏代码
packagetest;
importjava.util.List;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importcom.jiang.common.Pagination;
importcom.jiang.common.UserParamDTO;
importcom.jiang.entity.User;
importcom.jiang.service.UserService;
importcom.jiang.service.impl.UserServiceImpl;
publicclassMybatisSprintTest{
publicstaticvoidmain(String[]args){
ApplicationContextctx=newClassPathXmlApplicationContext("config/applicationContext.xml");
UserServiceus=ctx.getBean(UserServiceImpl.class);
//插入测试,成功返回自动生成的主键ID
Useruser1=newUser();
user1.setUserName("888");
user1.setUserAge(8);
LonginsertId=us.insertUser(user1);
System.out.println("INSERT:"+insertId);
//修改测试,成功返回1,失败返回0
Useruser2=newUser();
user2.setId(1L);
user2.setUserAddress("AAA");
IntegerupdateInteger=us.updateUser(user2);
System.out.println("UPDATE:"+updateInteger);
//删除测试,成功返回1,失败返回0
IntegerdeleteInteger=us.deleteUser(1L);
System.out.println("DELETE:"+deleteInteger);
//单个查询
Useruser3=us.getUserById(1L);
if(user3!=null){
System.out.println("SELECT-ONE:"+user3.getUserName());
}
//列表查询
Useruser4=newUser();
user4.setUserAge(5);
List<User>userList=us.getUserList(user4);
System.out.println("SELECT-LIST:"+userList.size());
//分页查询
UserParamDTOuserParamDTO=newUserParamDTO();
userParamDTO.setUserAddress("AAA");
userParamDTO.setPageNum(1);
Pagination<User>pUser=us.getPageUser(userParamDTO);
System.out.println("SELECT-PAGE:"+pUser.getDatas().size());
}
}