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和分页查询的更多相关文章

  1. MyBatis 中 Mapper 接口的使用原理

    MyBatis 中 Mapper 接口的使用原理 MyBatis 3 推荐使用 Mapper 接口的方式来执行 xml 配置中的 SQL,用起来很方便,也很灵活.在方便之余,想了解一下这是如何实现的, ...

  2. 5.7 Liquibase:与具体数据库独立的追踪、管理和应用数据库Scheme变化的工具。-mybatis-generator将数据库表反向生成对应的实体类及基于mybatis的mapper接口和xml映射文件(类似代码生成器)

    一. liquibase 使用说明 功能概述:通过xml文件规范化维护数据库表结构及初始化数据. 1.配置不同环境下的数据库信息 (1)创建不同环境的数据库. (2)在resource/liquiba ...

  3. mybatis从mapper接口跳转到相应的xml文件的eclipse插件

    mybatis从mapper接口跳转到相应的xml文件的eclipse插件 前提条件 开发软件 eclipse 使用框架 mybatis 为了方便阅读源码,项目使用mybatis的时候,方便从mapp ...

  4. Mybatis的Mapper接口方法不能重载

    今天给项目的数据字典查询添加通用方法,发现里边已经有了一个查询所有数据字典的方法 List<Dict> selectDictList(); 但我想设置的方法是根据数据字典的code查询出所 ...

  5. 防SQL注入:生成参数化的通用分页查询语句

    原文:防SQL注入:生成参数化的通用分页查询语句 前些时间看了玉开兄的“如此高效通用的分页存储过程是带有sql注入漏洞的”这篇文章,才突然想起某个项目也是使用了累似的通用分页存储过程.使用这种通用的存 ...

  6. MyBatis绑定Mapper接口参数到Mapper映射文件sql语句参数

    一.设置paramterType 1.类型为基本类型 a.代码示例 映射文件: <select id="findShopCartInfoById" parameterType ...

  7. Mybatis的mapper接口接受的参数类型

    最近项目用到了Mybatis,学一下记下来. Mybatis的Mapper文件中的select.insert.update.delete元素中有一个parameterType属性,用于对应的mappe ...

  8. mybatis的mapper接口代理使用的三个规范

    1.什么是mapper代理接口方式? MyBatis之mapper代理方式.mapper代理使用的是JDK的动态代理策略 2.使用mapper代理方式有什么好处 使用这种方式可以不用写接口的实现类,免 ...

  9. MyBatis的Mapper接口以及Example的实例函数及详解

    来源:https://blog.csdn.net/biandous/article/details/65630783 一.mapper接口中的方法解析 mapper接口中的函数及方法 方法 功能说明 ...

随机推荐

  1. JS互相调用

    JS互相调用 例1: <html> <head> <meta charset="UTF-8"> <script type="te ...

  2. SVN工作副本已经锁定错误的解决方法

    SVN工作副本锁定错误的解决方法 我们在使用svn版本控制软件时,时常会遇到想要更新本地项目的版本,却突然提示:工作副本已锁定.截图如下: 这种错误让人感觉很不舒服,实际上自己也没做过什么操作就这样了 ...

  3. SQL中Truncate语法

    转自:http://www.studyofnet.com/news/555.html 本文导读:删除表中的数据的方法有delete,truncate, 其中TRUNCATE TABLE用于删除表中的所 ...

  4. PAT_A1025#PAT Ranking

    Source: PAT A1025 PAT Ranking Description: Programming Ability Test (PAT) is organized by the Colleg ...

  5. MySQL数据库(一)—— 数据库介绍、MySQL安装、基础SQL语句

    数据库介绍.MySQL安装.基础SQL语句 一.数据库介绍 1.什么是数据库 数据库即存储数据的仓库 2.为什么要用数据库 (1)用文件存储是和硬盘打交道,是IO操作,所以有效率问题 (2)管理不方便 ...

  6. Java.util.ArrayDeque类

    java.util.ArrayDeque 类提供了可调整大小的阵列,并实现了Deque接口.以下是关于阵列双端队列的要点: 数组双端队列没有容量限制,使他们增长为必要支持使用. 它们不是线程安全的;如 ...

  7. 20140513 matlab画图

    1.matlab画图 x1=[1.00E-06,2.00E-06,4.00E-06,9.00E-06,2.00E-05,4.00E-05,8.00E-05,2.00E-04,4.00E-04,7.00 ...

  8. testNG官方文档翻译-3 testng.xml

    你可以通过以下几种不同的方法触发TestNG: 用一个testng.xml文件 使用ant 从命令行触发 这个章节将会介绍testng.xml的格式(你也可以在下面找到关于ant和命令行的内容). 关 ...

  9. python将字典列表导出为Excel文件的方法

    将如下的字典列表内容导出为Excel表格文件形式: ​ 关于上图字典列表的写入,请参考文章:https://blog.csdn.net/weixin_39082390/article/details/ ...

  10. 这是<一起找打的约定>的改良版本

    -- CREATE TABLE class ( -- cid INT(25)auto_increment PRIMARY KEY, -- caption VARCHAR(50) not NULL -- ...