首先介绍一下整合中用到的几个类
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配置文件中配置的SqlSessionTemplate Bean。笔者还是建议采用继承方式实现。废话不多说,开始吧
源码下载地址(包括所需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)
<?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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName" default-lazy-init="false">
<context:property-placeholder location="classpath:config/important.properties" />
<context:component-scan base-package="com.jiang" />
<context:annotation-config />
<bean id="sampleDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${db.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${db.url}</value>
</property>
<property name="user">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
<property name="initialPoolSize">
<value>${db.initialPoolSize}</value>
</property>
<property name="minPoolSize">
<value>${db.minPoolSize}</value>
</property>
<property name="maxPoolSize">
<value>${db.maxPoolSize}</value>
</property>
<property name="maxIdleTime">
<value>${db.maxIdleTime}</value>
</property>
<property name="acquireIncrement">
<value>${db.acquireIncrement}</value>
</property>
<property name="acquireRetryAttempts">
<value>${db.acquireRetryAttempts}</value>
</property>
<property name="acquireRetryDelay">
<value>${db.acquireRetryDelay}</value>
</property>
<property name="maxStatements">
<value>${db.maxStatements}</value>
</property>
<property name="maxStatementsPerConnection">
<value>${db.maxStatementsPerConnection}</value>
</property>
<property name="checkoutTimeout">
<value>${db.checkoutTimeout}</value>
</property>
<property name="breakAfterAcquireFailure">
<value>${db.breakAfterAcquireFailure}</value>
</property>
</bean>
<bean id="sampleSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="sampleDataSource" />
<property name="configLocation" value="config/Configuration.xml" />
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sampleSqlSessionFactory" />
</bean>
</beans>
2)MyBatis主配置文件(src/config/Configuration.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>
<mappers>
<mapper resource="com/jiang/dao/mapper/User.xml"/>
</mappers>
</configuration>
3)数据源配置属性(src/important.properties)
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)
package com.jiang.entity;
public class User {
private Long id;
private String userName;
private int userAge;
private String userAddress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
4. DAO
1)接口(src/com/jiang/dao/ISuperDAO.java)
package com.jiang.dao;
import java.util.List;
import java.util.Map;
import com.jiang.common.BasePageDTO;
import com.jiang.common.Pagination;
import com.jiang.entity.User;
public interface ISuperDAO {
public Long insert(String statementName, User parameterObject);
public Integer update(String statementName, Object parameterObject);
public Integer delete(String statementName, Object parameterObject);
public <T> T getObject(String statementName, Object parameterObject);
public <T> List<T> getList(String statementName, Object parameterObject);
public <T, V> Map<T, V> getMap(String statementName, Object parameterObject, String key);
public Pagination queryPagination(String statementName, BasePageDTO baseParamDto);
}
2)实现(src/com/jiang/dao/SuperDAO.java)
package com.jiang.dao;
import java.util.List;
import java.util.Map;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.jiang.common.BasePageDTO;
import com.jiang.common.Pagination;
import com.jiang.entity.User;
@Repository
public class SuperDAO extends SqlSessionDaoSupport implements ISuperDAO {
@Override
public Long insert(String statementName, User parameterObject) {
this.getSqlSession().insert(statementName, parameterObject);
return (long) parameterObject.getId();
}
@Override
public Integer update(String statementName, Object parameterObject) {
return this.getSqlSession().update(statementName, parameterObject);
}
@Override
public Integer delete(String statementName, Object parameterObject) {
return this.getSqlSession().delete(statementName, parameterObject);
}
@Override
public <T> T getObject(String statementName, Object parameterObject) {
return (T) this.getSqlSession().selectOne(statementName, parameterObject);
}
@Override
public <T> List<T> getList(String statementName, Object parameterObject) throws DataAccessException {
return this.getSqlSession().selectList(statementName, parameterObject);
}
@Override
public <T, V> Map<T, V> getMap(String statementName, Object parameterObject, String key) {
return this.getSqlSession().selectMap(statementName, parameterObject, key);
}
@Override
public Pagination queryPagination(String statementName, BasePageDTO baseParamDTO) {
if (baseParamDTO == null) {
return null;
}
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));
Integer totalCount = (Integer) this.getSqlSession().selectOne(statementName + "-count", baseParamDTO);
List resultList = this.getSqlSession().selectList(statementName, baseParamDTO);
return new Pagination(baseParamDTO.getPageSize(), baseParamDTO.getPageNum(), totalCount, resultList);
}
}
5. Mapper(src/com/jiang/dao/mapper/User.java)
<?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="UserEntityMapper">
<resultMap type="com.jiang.entity.User" id="BaseResultMap">
<id column="id" property="id" />
<result column="user_name" property="userName" />
<result column="user_age" property="userAge" />
<result column="user_address" property="userAddress" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, user_age, user_address
</sql>
<sql id="paginationSuffix">
limit #{startIdx,jdbcType=DECIMAL},#{pageSize,jdbcType=DECIMAL}
</sql>
<!-- 注意:Oracle返回ID要用 SELECT LOGS_SEQ.nextval AS ID FROM DUAL -->
<insert id="insertUser" parameterType="com.jiang.entity.User">
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
insert into user(
user_name
<if test="userAge != null">
,user_age
</if>
,user_address
)
values (
#{userName,jdbcType=VARCHAR}
<if test="userAge != null">
,#{userAge,jdbcType=VARCHAR}
</if>
,#{userAddress,jdbcType=VARCHAR}
)
</insert>
<update id="updateUser" parameterType="com.jiang.entity.User" >
update user
set
user_address = #{userAddress,jdbcType=VARCHAR}
where
id = #{id,jdbcType=VARCHAR}
<![CDATA[ and user_age < 10 ]]>
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
<select id="getUserByID" parameterType="int" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/>
from user where id = #{id}
</select>
<select id="getUserList" parameterType="com.jiang.entity.User" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/>
from user where user_age > #{userAge,jdbcType=VARCHAR}
</select>
<select id="getPageUser" parameterType="com.jiang.common.UserParamDTO" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/>
from user where user_address = #{userAddress,jdbcType=VARCHAR}
<include refid="paginationSuffix"/>
</select>
<select id="getPageUser-count" parameterType="com.jiang.common.UserParamDTO" resultType="java.lang.Integer">
select count(1)
from user where user_address = #{userAddress,jdbcType=VARCHAR}
</select>
</mapper>
6. 工具类(分页需要用到)
1)分页基类(src/com/jiang/common/BasePageDTO.java)
package com.jiang.common;
import java.io.Serializable;
import java.util.Date;
/**
* 分页查询基本传入参数
*/
public class BasePageDTO implements Serializable {
private static final long serialVersionUID = -3378378237423457439L;
private Date begin;
private Date end;
/**
* 分页使用的参数,分页大小
*/
private Integer pageSize;
/**
* 分页使用的参数,当前分页号
*/
private Integer pageNum;
/**
* 查询记录开始行号
*/
private Integer startIdx;
/**
* 查询记录结束行号
*/
private Integer endIdx;
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getStartIdx() {
return startIdx;
}
public void setStartIdx(Integer startIdx) {
this.startIdx = startIdx;
}
public Integer getEndIdx() {
return endIdx;
}
public void setEndIdx(Integer endIdx) {
this.endIdx = endIdx;
}
public Date getBegin() {
return begin;
}
public void setBegin(Date begin) {
this.begin = begin;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
}
2)User分页DTO(src/com/jiang/common/UserParamDTO.java)
package com.jiang.common;
public class UserParamDTO extends BasePageDTO{
private static final long serialVersionUID = 5281918320758904576L;
private String userAddress;
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
3)分页返回对象(src/com/jiang/common/Pagination.java)
package com.jiang.common;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* 分页
*/
public class Pagination<P> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 默认分页大小
*/
public static final int DEFAULT_PAGE_SIZE = 20;
/**
* 默认页码
*/
public static final int DEFAULT_PAGE_NUM = 1;
/**
* 分页使用的参数,分页大小
*/
private int pageSize;
/**
* 分页使用的参数,当前分页号
*/
private int pageNum;
/**
* 分页使用的参数,总数据条数
*/
private int totalCount;
/**
* 分页使用的参数,总页数
*/
private int pageCount;
/**
* 查询结果数据
*/
private List<P> datas = null;
public Pagination(int pageSize, int pageNum, int totalCount, List<P> datas) {
this.pageSize = pageSize;
this.pageNum = pageNum;
this.totalCount = totalCount;
this.datas = datas;
if (this.pageSize == 0) {
pageCount = 0;
} else if (this.totalCount % this.pageSize == 0) {
pageCount = this.totalCount / this.pageSize;
} else {
pageCount = totalCount / this.pageSize + 1;
}
}
public int getPageSize() {
return pageSize;
}
public int getPageNum() {
return pageNum;
}
public int getTotalCount() {
return totalCount;
}
public int getPageCount() {
return this.pageCount;
}
public List<P> getDatas() {
return datas;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
7. Service
1)接口(src/com/jiang/service/UserService.java)
package com.jiang.service;
import java.util.List;
import com.jiang.common.Pagination;
import com.jiang.common.UserParamDTO;
import com.jiang.entity.User;
public interface UserService {
public Long insertUser(User user);
public Integer updateUser(User user);
public Integer deleteUser(Long id);
public User getUserById(Long id);
public List<User> getUserList(User user);
public Pagination<User> getPageUser(UserParamDTO userParamDTO);
}
2)实现(src/com/jiang/service/impl/UserServiceImpl.java)
package com.jiang.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.jiang.common.Pagination;
import com.jiang.common.UserParamDTO;
import com.jiang.dao.ISuperDAO;
import com.jiang.entity.User;
import com.jiang.service.UserService;
@Component("userService")
public class UserServiceImpl implements UserService {
@Resource
private ISuperDAO superDAO;
@Override
public Long insertUser(User user) {
return superDAO.insert("UserEntityMapper.insertUser", user);
}
@Override
public Integer updateUser(User user){
return superDAO.update("UserEntityMapper.updateUser", user);
}
@Override
public Integer deleteUser(Long id){
return superDAO.delete("UserEntityMapper.deleteUser", id);
}
@Override
public User getUserById(Long id) {
return superDAO.getObject("UserEntityMapper.getUserByID", id);
}
@Override
public List<User> getUserList(User user) {
return superDAO.getList("UserEntityMapper.getUserList", user);
}
@Override
public Pagination<User> getPageUser(UserParamDTO userParamDTO) {
return superDAO.queryPagination("UserEntityMapper.getPageUser", userParamDTO);
}
}
8. 测试类(src/test/MybatisSpringTest.java)
package test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jiang.common.Pagination;
import com.jiang.common.UserParamDTO;
import com.jiang.entity.User;
import com.jiang.service.UserService;
import com.jiang.service.impl.UserServiceImpl;
public class MybatisSprintTest {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
UserService us = ctx.getBean(UserServiceImpl.class);
// 插入测试,成功返回自动生成的主键ID
User user1 = new User();
user1.setUserName("888");
user1.setUserAge(8);
Long insertId = us.insertUser(user1);
System.out.println("INSERT:" + insertId);
// 修改测试,成功返回1,失败返回0
User user2 = new User();
user2.setId(1L);
user2.setUserAddress("AAA");
Integer updateInteger = us.updateUser(user2);
System.out.println("UPDATE:" + updateInteger);
// 删除测试,成功返回1,失败返回0
Integer deleteInteger = us.deleteUser(1L);
System.out.println("DELETE:" + deleteInteger);
// 单个查询
User user3 = us.getUserById(1L);
if(user3 != null){
System.out.println("SELECT-ONE:" + user3.getUserName());
}
// 列表查询
User user4 = new User();
user4.setUserAge(5);
List<User> userList = us.getUserList(user4);
System.out.println("SELECT-LIST:" + userList.size());
// 分页查询
UserParamDTO userParamDTO = new UserParamDTO();
userParamDTO.setUserAddress("AAA");
userParamDTO.setPageNum(1);
Pagination<User> pUser = us.getPageUser(userParamDTO);
System.out.println("SELECT-PAGE:" + pUser.getDatas().size());
}
}