Spring整合MyBatis
编程技术  /  houtizong 发布于 3年前   108
<?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>
<?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>
db.transaction.attributes=PROPAGATION_REQUIRED,-Exceptiondb.driverClassName=com.mysql.jdbc.Driverdb.url=jdbc:mysql://127.0.0.1:3306/mybatisdb.username=rootdb.password=1234db.initialPoolSize=5db.minPoolSize=2db.maxPoolSize=5db.maxIdleTime=60db.acquireIncrement=3db.acquireRetryAttempts=30db.acquireRetryDelay=2000db.maxStatements=10db.maxStatementsPerConnection=10db.checkoutTimeout=0db.breakAfterAcquireFailure=false
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;}}
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);}
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;@Repositorypublic 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); }}
<?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>
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; }}
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; }}
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); }}
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);}
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); }}
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()); }}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接