Mybatis 使用Mapper接口的Sql动态代码方式进行CURD和分页查询
1、Maven的pom.xml
2、配置文件
2.1、db.properties
2.2、mybatis.xml
2.3、log4j.xml
3、MybatisUtil工具类
4、Mapper映射文件
<?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="com.mcs.mapper.EmployeeMapper">
<resultMap id="employeeResultMap" type="com.mcs.entity.Employee">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="birthday" property="birthday" jdbcType="DATE" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="telephone" property="telephone" jdbcType="VARCHAR" />
<result column="cellphone" property="cellphone" jdbcType="VARCHAR" />
<result column="address" property="address" jdbcType="VARCHAR" />
<result column="department_id" property="departmentId" jdbcType="INTEGER" />
</resultMap> <!-- 新增职员,并返回插入后的ID值 -->
<insert id="add" keyColumn="id" keyProperty="id" useGeneratedKeys="true" parameterType="Employee">
insert into t_employee
( name, sex, birthday, email, telephone, cellphone, address, department_id )
values
( #{name}, #{sex}, #{birthday}, #{email}, #{telephone}, #{cellphone}, #{address}, #{departmentId} )
</insert> <update id="updateById" parameterType="Employee">
update t_employee
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=DATE},
email = #{email,jdbcType=VARCHAR},
telephone = #{telephone,jdbcType=VARCHAR},
cellphone = #{cellphone,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR},
department_id = #{departmentId,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update> <delete id="deleteById" parameterType="Integer">
delete from t_employee
where id = #{id}
</delete> <select id="findById" parameterType="Integer" resultMap="employeeResultMap">
select
id,name, sex, birthday, email, telephone, cellphone, address, department_id
from t_employee
where id = #{id}
</select> <!-- 基本字段 -->
<sql id="baseColumn">
id,name, sex, birthday, email, telephone, cellphone, address, department_id
</sql> <sql id="whereParam">
<where>
<if test="id!=null">
id = #{id}
</if>
<if test="name!=null">
name like #{name}
</if>
<if test="sex!=null">
sex = #{sex}
</if>
<if test="departmentId!=null">
department_id = #{departmentId}
</if>
</where>
</sql>
<!-- 动态查询与分页 -->
<select id="findListByDynamic" parameterType="EmployeeCustom" resultMap="employeeResultMap">
select
<include refid="baseColumn"></include>
from t_employee
<include refid="whereParam"></include>
<if test="pageNo!=null">
<if test="pageSize!=null">
limit #{pageNo}, #{pageSize}
</if>
</if>
</select>
<select id="findListByDynamicCount" parameterType="EmployeeCustom" resultType="Long">
select count(id) totalNumber
from t_employee
<include refid="whereParam"></include>
</select> <!-- 动态更新 -->
<update id="dynamicUpdateById" parameterType="Employee">
update t_employee
<!-- set标签自动判断哪个是最后一个字段,会自动去掉最后一个,号 -->
<set>
<if test="name!=null">
name = #{name},
</if>
<if test="sex!=null">
sex = #{sex},
</if>
<if test="birthday!=null">
birthday = #{birthday},
</if>
<if test="email!=null">
email = #{email},
</if>
<if test="telephone!=null">
telephone = #{telephone},
</if>
<if test="cellphone!=null">
cellphone = #{cellphone},
</if>
<if test="address!=null">
address = #{address},
</if>
<if test="departmentId!=null">
department_id = #{departmentId},
</if>
</set>
where id = #{id}
</update> <!-- 动态批量删除,参数:Integer[] ids delete from t_employee where id in (,,) -->
<delete id="dynamicDeleteByArray">
delete from t_employee where id in
<!-- foreach用于迭代数组元素 open表示开始符号 close表示结束符合 separator表示元素间的分隔符 item表示迭代的数组,属性值可以任意,但提倡与方法的数组名相同 #{ids}表示数组中的每个元素值 -->
<foreach collection="array" open="(" close=")" separator="," item="ids">
#{ids}
</foreach>
</delete> <!-- 动态批量删除,参数:List<Integer> ids delete from t_employee where id in (,,) -->
<delete id="dynamicDeleteByList">
delete from t_employee where id in
<foreach collection="list" open="(" close=")" separator="," item="ids">
#{ids}
</foreach>
</delete> <sql id="key">
<!-- 去掉最后一个, -->
<trim suffixOverrides=",">
<if test="name!=null">
name,
</if>
<if test="sex!=null">
sex,
</if>
<if test="birthday!=null">
birthday,
</if>
<if test="email!=null">
email,
</if>
<if test="telephone!=null">
telephone,
</if>
<if test="cellphone!=null">
cellphone,
</if>
<if test="address!=null">
address,
</if>
<if test="departmentId!=null">
department_id,
</if>
</trim>
</sql>
<sql id="value">
<!-- 去掉最后一个, -->
<trim suffixOverrides=",">
<if test="name!=null">
#{name},
</if>
<if test="sex!=null">
#{sex},
</if>
<if test="birthday!=null">
#{birthday},
</if>
<if test="email!=null">
#{email},
</if>
<if test="telephone!=null">
#{telephone},
</if>
<if test="cellphone!=null">
#{cellphone},
</if>
<if test="address!=null">
#{address},
</if>
<if test="departmentId!=null">
#{departmentId},
</if>
</trim>
</sql>
<!-- 动态增加 -->
<insert id="dynamicInsert" parameterType="Employee">
insert into t_employee(<include refid="key"/>) values(<include refid="value"/>)
</insert> </mapper>
5、Mapper映射文件对应的接口文件
package com.mcs.mapper; import java.util.List; import com.mcs.entity.Employee;
import com.mcs.entity.EmployeeCustom; public interface EmployeeMapper {
/**
* 新增员工
*/
public void add(Employee employee) throws Exception;
/**
* 根据Id修改员工
*/
public void updateById(Employee employee) throws Exception;
/**
* 根据ID删除员工
*/
public void deleteById(Integer id) throws Exception;
/**
* 根据ID查找员工
*/
public Employee findById(Integer id) throws Exception;
/**
* 根据输入参数,动态查找员工,可分页
*/
public List<Employee> findListByDynamic(EmployeeCustom employeeCustom) throws Exception;
/**
* 根据输入参数,动态合计员工记录数量
*/
public Long findListByDynamicCount(EmployeeCustom employeeCustom) throws Exception;
/**
* 根据输入参数,动态更新
*/
public void dynamicUpdateById(Employee employee) throws Exception;
/**
* 根据输入的Array参数,动态删除
*/
public void dynamicDeleteByArray(Integer[] ids) throws Exception;
/**
* 根据输入List参数,动态删除
*/
public void dynamicDeleteByList(List<Integer> ids) throws Exception;
/**
* 根据输入参数,动态插入
*/
public void dynamicInsert(Employee employee) throws Exception;
}
此文件应与Mapper在同一命名空间下
6、测试代码
package com.mcs.test; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.mcs.entity.Employee;
import com.mcs.entity.EmployeeCustom;
import com.mcs.mapper.EmployeeMapper;
import com.mcs.util.MybatisUtil; public class TestEmployeeMapper {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TestEmployeeMapper.class); private EmployeeMapper employeeMapper;
private SqlSession sqlSession = null; @Before
public void init() {
sqlSession = MybatisUtil.getSqlSession();
employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
} @After
public void destory() {
MybatisUtil.closeSqlSession();
} @Test
public void testFindById() throws Exception {
Employee employee = employeeMapper.findById();
logger.debug(employee);
} @Test
public void testFindAll() throws Exception {
List<Employee> employees = employeeMapper.findListByDynamic(null);
logger.debug(employees);
Long totalNumber = employeeMapper.findListByDynamicCount(null);
logger.debug("共" + totalNumber + "条记录");
} @Test
public void testAdd() throws Exception {
Employee employee = new Employee();
employee.setName("赵小凤");
employee.setSex("female");
employee.setBirthday(new Date());
employee.setEmail("xiaofeng@126.com");
try {
employeeMapper.add(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug(employee);
} @Test
public void testEditById() throws Exception {
Employee employee = employeeMapper.findById();
employee.setDepartmentId();
employee.setAddress("天津"); try {
employeeMapper.updateById(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug(employee);
} @Test
public void testDeleteById() throws Exception {
Employee employee = employeeMapper.findById();
logger.debug(employee);
try {
employeeMapper.deleteById();
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug("已成功删除员工:" + employee.getName());
} @Test
public void testFindListByParam() throws Exception {
EmployeeCustom employeeCustom = new EmployeeCustom();
employeeCustom.setSex("male");
employeeCustom.setPageNo( * );
employeeCustom.setPageSize(); List<Employee> employees = employeeMapper.findListByDynamic(employeeCustom);
for (Employee employee : employees) {
logger.debug(employee.getName());
} Long totalNumber = employeeMapper.findListByDynamicCount(employeeCustom);
if (employees.size() > ) {
logger.debug("当前第" + (employeeCustom.getPageNo() + ) + "页");
logger.debug("每页" + employeeCustom.getPageSize() + "条记录");
logger.debug("共" + totalNumber + "条记录");
}
} @Test
public void testDynamicUpdateByID() throws Exception {
Employee employee = new Employee();
employee.setId();
employee.setName("张丽"); try {
employeeMapper.dynamicUpdateById(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} } @Test
public void testDynamicDeleteByArray() throws Exception {
Integer[] ids = new Integer[] { , , };
try {
employeeMapper.dynamicDeleteByArray(ids);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
}
} @Test
public void testDynamicDeleteByList() throws Exception {
List<Integer> ids = new ArrayList<Integer>();
ids.add();
ids.add();
ids.add(); try {
employeeMapper.dynamicDeleteByList(ids);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
}
} @Test
public void testDynamicInsert() throws Exception {
Employee employee = new Employee();
employee.setName("赵小梅");
employee.setSex("female"); try {
employeeMapper.dynamicInsert(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
}
} }
Mybatis 使用Mapper接口的Sql动态代码方式进行CURD和分页查询的更多相关文章
- MyBatis 中 Mapper 接口的使用原理
MyBatis 中 Mapper 接口的使用原理 MyBatis 3 推荐使用 Mapper 接口的方式来执行 xml 配置中的 SQL,用起来很方便,也很灵活.在方便之余,想了解一下这是如何实现的, ...
- 5.7 Liquibase:与具体数据库独立的追踪、管理和应用数据库Scheme变化的工具。-mybatis-generator将数据库表反向生成对应的实体类及基于mybatis的mapper接口和xml映射文件(类似代码生成器)
一. liquibase 使用说明 功能概述:通过xml文件规范化维护数据库表结构及初始化数据. 1.配置不同环境下的数据库信息 (1)创建不同环境的数据库. (2)在resource/liquiba ...
- mybatis从mapper接口跳转到相应的xml文件的eclipse插件
mybatis从mapper接口跳转到相应的xml文件的eclipse插件 前提条件 开发软件 eclipse 使用框架 mybatis 为了方便阅读源码,项目使用mybatis的时候,方便从mapp ...
- Mybatis的Mapper接口方法不能重载
今天给项目的数据字典查询添加通用方法,发现里边已经有了一个查询所有数据字典的方法 List<Dict> selectDictList(); 但我想设置的方法是根据数据字典的code查询出所 ...
- 防SQL注入:生成参数化的通用分页查询语句
原文:防SQL注入:生成参数化的通用分页查询语句 前些时间看了玉开兄的“如此高效通用的分页存储过程是带有sql注入漏洞的”这篇文章,才突然想起某个项目也是使用了累似的通用分页存储过程.使用这种通用的存 ...
- MyBatis绑定Mapper接口参数到Mapper映射文件sql语句参数
一.设置paramterType 1.类型为基本类型 a.代码示例 映射文件: <select id="findShopCartInfoById" parameterType ...
- Mybatis的mapper接口接受的参数类型
最近项目用到了Mybatis,学一下记下来. Mybatis的Mapper文件中的select.insert.update.delete元素中有一个parameterType属性,用于对应的mappe ...
- mybatis的mapper接口代理使用的三个规范
1.什么是mapper代理接口方式? MyBatis之mapper代理方式.mapper代理使用的是JDK的动态代理策略 2.使用mapper代理方式有什么好处 使用这种方式可以不用写接口的实现类,免 ...
- MyBatis的Mapper接口以及Example的实例函数及详解
来源:https://blog.csdn.net/biandous/article/details/65630783 一.mapper接口中的方法解析 mapper接口中的函数及方法 方法 功能说明 ...
随机推荐
- VS2010 下C++使用UTF8编码
http://www.nubaria.com/en/blog/?p=289 #pragma execution_character_set("utf-8")
- CodeForces-1249C2-Good Numbers (hard version) -巧妙进制/暴力
The only difference between easy and hard versions is the maximum value of n. You are given a positi ...
- 【Java多线程系列随笔一】浅析 Java Thread.join()
一.在研究join的用法之前,先明确两件事情. 1.join方法定义在Thread类中,则调用者必须是一个线程, 例如: Thread t = new CustomThread(); //这里一般是自 ...
- ubuntu 无pthread
由于学习多线程编程,所以用到pthread,但是man的时候却发现没有pthread函数库的手册页,然后安装 $sudo apt-get install glibc-doc 安装以后,发现还是有很多函 ...
- JAVA API 实现hdfs文件操作
java api 实现hdfs 文件操作会出现错误提示: Permission denied: user=hp, access=WRITE, inode="/":hdfs:supe ...
- python xlwt设置单元格的自定义背景颜色
我使用python 2.7和xlwt模块进行excel导出 我想设置我知道可以使用的单元格的背景颜色 style1 = xlwt.easyxf('pattern: pattern solid, for ...
- js 正则替换的使用方法
function compress(source) { const keys = {}; ⇽--- 存储目标key source.replace( /([^=&]+)=([^&]*)/ ...
- 前端 JavaScript BOM & DOM
内容目录: 1. BOM 2. DOM BOM(Browser Object Model)是指浏览器对象模型,它使 JavaScript 有能力与浏览器进行"对话". DOM (D ...
- 深度探索C++对象模型之第四章:函数语义学
C++有三种类型的成员函数:1.static/nonstatic/virtual 一.成员的各种调用方式 C with Classes 只支持非静态成员函数(Nonstatic Member Func ...
- Spring常见面试题及答案解析
.说一下spring中Bean的作用域 singleton: Spring IoC容器中只会存在一个共享的Bean实例,无论有多少个Bean引用它,始终指向同一对象.Singleton作用域是Spri ...