- 浏览: 5670 次
Spring整合MyBatis(转载地址: http://ccbbkk.iteye.com/blog/2066588 )
博客分类:
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配置文件中配置的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)
Java代码 收藏代码
<?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)
Java代码 收藏代码
<?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)
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代码 收藏代码
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)
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)
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)
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)
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)
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)
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)
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)
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)
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());
}
}
博客分类:
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配置文件中配置的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)
Java代码 收藏代码
<?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)
Java代码 收藏代码
<?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)
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代码 收藏代码
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)
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)
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)
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)
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)
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)
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)
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)
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)
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());
}
}
相关推荐
**Spring整合Mybatis原理分析** 在Java Web开发中,Spring框架以其强大的依赖注入和面向切面编程能力,成为了事实上的核心框架。Mybatis则是一个轻量级的持久层框架,它简化了数据库操作,提供了直观的SQL映射。将...
本文将深入探讨如何进行"Spring整合Mybatis"的基础搭建,以及涉及到的相关技术点。 首先,Spring框架是一个开源的应用程序框架,它简化了Java EE应用的开发,提供了依赖注入(DI)和面向切面编程(AOP)等功能。在...
在Spring整合MyBatis的过程中,我们需要在该文件中声明以下关键组件: 1. **数据源(DataSource)**: 数据源定义了如何连接到数据库。Spring支持多种数据源实现,如Apache的DBCP或Tomcat的JDBC数据源。配置中通常...
在Java开发领域,Spring...以上就是Spring集成Mybatis所需的jar包及集成过程中的关键配置和步骤。正确配置这些组件,可以让我们在享受Spring的便利性的同时,充分利用MyBatis的灵活性和高效性,实现高质量的Java应用。
**七、Spring整合MyBatis配置** 1. 在Spring的配置文件`applicationContext.xml`中,配置DataSource、SqlSessionFactory和MapperScannerConfigurer。 2. 配置`mybatis-spring`的`SqlSessionFactoryBean`,指定...
本文将深入探讨如何将Spring与MyBatis进行整合,以及在整合过程中可能遇到的问题和解决方案。 首先,整合Spring与MyBatis的核心在于Spring的DataSource、TransactionManager和SqlSessionFactoryBean。DataSource是...
3. MyBatis-Spring整合库:mybatis-spring。 4. 数据库驱动:如mysql-connector-java(对于MySQL)、ojdbc(对于Oracle)等。 5. 其他依赖库:如log4j或slf4j用于日志记录,asm、cglib等用于AOP代理。 整合过程大致...
下面将详细介绍在Spring整合MyBatis3时所需的jar文件以及它们在整合过程中的作用。 1. **Spring核心模块**: - `spring-context`: 提供了应用上下文和依赖注入的核心接口,是Spring框架的基础。 - `spring-beans`...
Spring整合Mybatis源码解析
在本项目中,我们主要探讨的是如何在IntelliJ IDEA(IDEA)环境下,整合Spring、Mybatis和SpringMVC(SSM)框架,并利用PageHelper分页插件实现高效的数据分页。以下是对这些技术及其整合过程的详细说明: 1. **...
在本项目中,“Spring整合Mybatis简单项目”旨在教授初学者如何将两个流行的Java框架——Spring和Mybatis结合,以实现一个简单的影视资源管理系统。这个系统可能会包括资源的增删改查、分类管理等功能,帮助用户高效...
官方Spring整合Mybatis所需jar包,意味着我们需要确保安装的库文件能够支持这两者之间的无缝协作。Mybatis-3.4.6.jar是Mybatis的主要库文件,包含了Mybatis的核心功能,包括SQL映射文件解析、SQL执行、结果映射等。...
首先,Spring整合MyBatis主要是通过Spring的SqlSessionFactoryBean和MapperScannerConfigurer来完成的。SqlSessionFactoryBean用于创建MyBatis的SqlSessionFactory,它是MyBatis的核心,负责管理SqlSession。...
这是一个web程序的后台代码,整合了spring mvc和mybatis的配置,实现了各地方的电量增删改查,该代码持久层利用mybatis框架,简化了dao层的实现,spring实现了controller层、service层。
将两者整合,形成的SSM(Spring、SpringMVC、Mybatis)架构是Java Web开发中的常见选择。现在我们来详细讨论一下Spring-Mybatis整合的相关知识点。 1. **Spring 概述**: Spring 是一个全面的企业级应用框架,它...
下面我们将详细探讨Spring整合MyBatis过程中所需的jar包以及它们的作用。 1. **Spring框架核心库**: - `spring-context`: 提供了核心的上下文功能,包括依赖注入(DI)和bean工厂。 - `spring-beans`: 包含了...
Spring整合Mybatis是Java开发中常见的一种技术组合,它将Spring的IoC(Inversion of Control,控制反转)和AOP(Aspect Oriented Programming,面向切面编程)能力与Mybatis的灵活SQL映射功能结合,提高了开发效率并...
例如Spring框架核心包、Spring JDBC包、MyBatis核心包以及MyBatis与Spring整合包等。文中提到的版本为Spring 5.2.7.RELEASE和MyBatis 3.5.5,MyBatis-Spring 2.0.4,同时也需要添加数据库连接驱动(如文中提到的...
总之,Spring整合MyBatis的过程涉及到依赖管理、配置文件设置、数据源和事务管理的配置,以及Mapper接口和XML文件的编写。这种整合方式使得开发人员可以充分利用Spring的IoC和AOP特性,同时享受MyBatis提供的灵活的...