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接口中的函数及方法 方法 功能说明 ...
随机推荐
- 用java进行测试php写的接口
<?php /* * @Author: anchen * @Date: 2018-07-06 13:53:19 * @Last Modified by: anchen * @Last Modif ...
- 2016 ICPC Mid-Central USA Region J. Windy Path (贪心)
比赛链接:2016 ICPC Mid-Central USA Region 题目链接:Windy Path Description Consider following along the path ...
- Flink 配置文件详解
前面文章我们已经知道 Flink 是什么东西了,安装好 Flink 后,我们再来看下安装路径下的配置文件吧. 安装目录下主要有 flink-conf.yaml 配置.日志的配置文件.zk 配置.Fli ...
- 1044 Shopping in Mars (25 分)
Shopping in Mars is quite a different experience. The Mars people pay by chained diamonds. Each diam ...
- GIT 学习第二天 (二)
工作区和暂存区 工作区: 就是你在电脑里能看到的目录,比如:webgit 文件夹 就是一个工作区 版本库: 工作区有一个隐藏目录 .git ,这个不算工作区,而是Git的版本库 Git的版本库里存了很 ...
- 行动带来力量,周三(5月7日)晚IT讲座通知
讲座简单介绍 ITAEM团队负责人骆宏等和大家周三晚8点(5月7日)相约钟海楼03035.和大家分享团队成员的"编程入门之路",在这里,同龄人(大三)以学生的角度.和大家分 ...
- Asp.net Core + Log4net + ELK 搭建日志中心
原文:Asp.net Core + Log4net + ELK 搭建日志中心 Docker中一键安装ELK 对于这种工具类的东西,第一步就直接到docker的hub中查找了,很幸运,不仅有Elasti ...
- Java中++操作是同步的吗?为什么?
不是同步的 因为++操作分为三步实现 内存到寄存器 寄存器自增操作 寄存器写回内存 这三步每一步都可以被打断,不是原子操作,所以不是同步操作
- 30个优秀的CSS技术和实例 By 彬Go 2008-12-04
在这里可发现很多与众不同的技术,比如:图片集.阴影效果.可扩展按钮.菜单等…这些实例都是使用纯CSS和HTML实现的.单击每个实例的标题可以被转向到该技术实例的相关教程或说明页面(英文),单击每个实例 ...
- NCM格式转换MP3格式
首先下载软件: 百度网盘下载地址:https://pan.baidu.com/s/1I_HUQGBnOq23Zdm-NgbnqA 提取码:u4m5 下载完毕直接打开就好 添加NCM文件 点击开始转换 ...