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. TLS/SSL 协议 - ServerKeyExchange、ServerHelloDone

    ServerKeyExchange ServerKeyExchange消息的目的是携带密钥交换的额外数据.消息内容对于不同的协商算法套件都会存在差异.在某些场景中,服务器不需要发送任何内容,这意味着在 ...

  2. Linux两台机器简历信任

    cd ~/.ssh ssh-keygen  -t  rsa scp ./id_rsa.pub root@192.168.1.1:/root/.ssh/authorized_keys

  3. 数据整理A

  4. SQLite 小调研

    一. 概况: SQLite 是 D. Richard Hipp 于 2000 年采用 C 语言编写的一个轻量级.跨平台的关系型数据库,支持大部分 SQL92 标准(比如视图.事务.触发器.blob 数 ...

  5. Center OS 部署Tomcat服务

    一.下载tomcat tomcat官网下载软件包,官网:https://tomcat.apache.org/ 点击download,进入下载页面,下载如下版本: 下载完成后用ftp上传到服务器,SSH ...

  6. time 类

    timeStamp = time.time() #获取当前的时间戳 print(timeStamp) # 1555555453.6283455 timeTuple = time.localtime(t ...

  7. Vue Router高级

    路由组件传参 通过props解耦 const User = { props: ['id'], template: '<div>User {{ id }}</div>' } co ...

  8. Windows中区位码转换为机内码

    步骤的简化 区位码的区和位分别加上32得到国标码, 再分别加上128得到机内码 区位码的区和位分别加上160得到机内码 区位码加上A0A0H = 机内码 示例: 我 我的区位码是4650 区位码 46 ...

  9. EF批量添加数据之修改SQL Server执行上限

    asp.net core 项目 打开Startup.cs services.AddDbContext<MyContext>( options => { options.UseSqlS ...

  10. Quick BI 支持多种数据源进行多维分析

    一.摘要 随着互联网的高速发展,数据量爆发式增长的同时,数据的存储形式也开始呈现出多样性,有结构化存储,如 Mysql, Oracle, SQLServer 等,半结构化甚至非结构化存储,如HBase ...