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接口中的函数及方法 方法 功能说明 ...
随机推荐
- TFS 中如何将项目加入已有的源代码管理器中?
Visual Studio 的某解决方案已经加入 Team Foundation Server,现在再将已经存在的项目加入到解决方案中,可是签入时,并没有把新加入的项目签入,怎么办呢? 在团队资源管理 ...
- TLS/SSL 协议 - ServerHello
ServerHello ServerHello消息的意义是将服务器选择的连接参数传送回客户端.这个消息的结构与ClientHello类似,只是每个字段只包含一个选项. 服务器无需支持客户端支持的最佳版 ...
- 【C++】清空一个C++栈的快速方法
来源:https://stackoverflow.com/questions/40201711/how-can-i-clear-a-stack-in-c-efficiently/40201744 传统 ...
- Python 操作excel常见异常
一.使用xlrd模块读取excel: 1.报错:IndexError: list index out of range,如下图 解决方法:reading_sheet.cell(1,0).value中c ...
- Spring Boot主要目标
Spring Boot主要目标 Spring Boot的主要目标是: 为所有Spring开发提供一个基本的,更快,更广泛的入门体验. 开箱即用,但随着需求开始偏离默认值,快速启动. 提供大型项目(例如 ...
- Spring Boot Restful WebAPI集成 OAuth2
系统采用前后端分离的架构,采用OAuth2协议是很自然的事情. 下面开始实战,主要依赖以下两个组件: <dependency> <groupId>org.springframe ...
- 启动多个mysql实例
如果使用./support-files/mysql.server 文件启动,则默认读取/etc/my.cnf 配置文件,这种方式有时候启动不了 会提示报错 :The server quit witho ...
- docker Dockerfile学习---nginx负载均衡tomcat服务
1.此过程在nginx的基础上,也就是上篇博客写的内容. 2.创建项目目录并上传包,解压 $ mkdir centos_tomcat $ cd centos_tomcat $ tar zxvf jdk ...
- mysql 查询正在执行的sql
select * from information_schema.`PROCESSLIST` where info is not null; 或者 -- use information_schema; ...
- 深度探索C++对象模型之第三章:数据语义学
如下三个类: class X { }: class Y :public virtual X { }; class Z : public virtual X {}; class A :public Y, ...