mybatis plus讲解
MyBatis
为什么要使用MyBatis
MyBatis学习路线
主要使用的标签有:
Mybatis使用
依赖
分页插件
配置
entity
example:
example使用
mapper
xml
分页
MyBatis-plus
mybatis plus使用
依赖
分页插件
配置
拼接查询条件
service:
IService
mapper:
xml
分页
mybatis plus讲解
mybatis plue 官网:https://mp.baomidou.com/
MyBatis
MyBatis前身是iBatis,是Clinton Begin在2001年发起的一个开源项目。最初侧重于码软件开发,后续发展成为一款基于java的持久层框架。Mybatis是一款优秀的持久层框架支持自定义SQL查询、存储过程和高级映射,消除了几乎所有的JDBC代码和参数的手动设置以及结果集的检索。MyBatis可以使用简单的XML或者注解进行映射和配置,通过将参数映射到配置的SQL最终解析为执行的SQL语句,查询后将SQl结果集映射成java对象返回。MyBatis提供的持久层框架包括SQL Maps(Mapper)和Data Access Objects(DAO),相对于Hibernate而言它提供的是一种把自动化的ORM实现。MyBatis中一级缓存会默认启用(本地缓存)且不受控制,一般说缓存时指的是MyBatis的二级缓存
为什么要使用MyBatis
JDBC存在一定的不足,例如:
- JDBC频繁连接和关闭资源,造成资源的浪费。
- JDBC对sql语句进行硬编码,sql语句比较分散,不易维护。
- JDBC在传递参数必须按照顺序传递参数,不能自由拼装sql语句,不灵活
- 结果映射必须手动封装到javabean。
而MyBatis可以解决JDBC的不足之处,程序员只需要关注sql语句,不需要把精力放在业务。适合需要变化多端的项目。
为了解决JDBC存在的问题和简化数据库操作,MyBatis提供了较为优秀的解决方案,例如:
- 可以通过主配置文件配置连接池解决频繁创建、释放数据库连接造成的性能影响。
- 动态SQL解决JDBC中硬编码问题:
- a) Where条件改变;
- b) 占位符位置变化。
- 可通过包装类方便的获取数据库查询结果集对象。
- 使Dao层业务逻辑和数据库访问分离更易维护和测试。
MyBatis学习路线
- 了解MyBatis架构;
- 掌握MyBatis框架搭建、配置;
- 使用MyBatis完成对数据库的增、删、改、查操作。
- 掌握Mapper代理开发;
- 掌握输入和输出映射;
- 掌握多表关联查询;
- 掌握动态SQL编写SQL语句;
- 使用MyBatis Generator工具快速生成Bean、Interface、mapper.xml;
- 掌握MyBatis+Spring开发(需要部分Spring知识)
主要使用的标签有:
<select></select>
对应注解@Select<update></update>
对应注解@Update<insert></insert>
对应注解@Insert<delete></delete>
对应注解@Delete<where></where>
在某些条件根据入参有无决定是可使用以避免1=1这种写法,也会根据是否为where条件后第一个条件参数自动去除and<if></if>
:类似于java中的条件判断if,没有<else>
标签<choose>
标签
<choose>
<when></when>
<otherwise></otherwise>
</choose>
<foreach></forwach>
:可以对数组、Map或实现了Iterable接口(如List、Set)的对象遍历。可实现in、批量更新、批量插入等。<resultMap></resultMap>
:映射结果集<resultType></resultType>
:映射结果类型,可是java实体类或Map、List等类型。
Mybatis使用
依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mybatis 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
分页插件
其实不配置也行,有默认配置的
bean配置方法
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
p.setProperty("dialect", "mysql");
pageHelper.setProperties(p);
return pageHelper;
}
或者直接在yml配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
配置
mybatis:
configuration:
map-underscore-to-camel-case: true # entity驼峰转换
mapper-locations: classpath:/mappers/**/*.xml #mapper的xml位置
type-aliases-package: com.cc.example.entity #mapper/xml中使用的entity位置
entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String id;
private String name;
private Integer types;
private Integer enable;
private String createby;
private String years;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createtime;
private String remark;
}
example:
mybatis代码生成的....很大的一个类
package com.cc.learn.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
user
*
* @mbg.generated Mon Jul 06 10:42:37 CST 2020
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("ID is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("ID is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(String value) {
addCriterion("ID =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(String value) {
addCriterion("ID <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(String value) {
addCriterion("ID >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(String value) {
addCriterion("ID >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(String value) {
addCriterion("ID <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(String value) {
addCriterion("ID <=", value, "id");
return (Criteria) this;
}
public Criteria andIdLike(String value) {
addCriterion("ID like", value, "id");
return (Criteria) this;
}
public Criteria andIdNotLike(String value) {
addCriterion("ID not like", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<String> values) {
addCriterion("ID in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<String> values) {
addCriterion("ID not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(String value1, String value2) {
addCriterion("ID between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(String value1, String value2) {
addCriterion("ID not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("NAME is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("NAME is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("NAME =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("NAME <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("NAME >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("NAME >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("NAME <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("NAME <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("NAME like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("NAME not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("NAME in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("NAME not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("NAME between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("NAME not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andTypesIsNull() {
addCriterion("TYPES is null");
return (Criteria) this;
}
public Criteria andTypesIsNotNull() {
addCriterion("TYPES is not null");
return (Criteria) this;
}
public Criteria andTypesEqualTo(Integer value) {
addCriterion("TYPES =", value, "types");
return (Criteria) this;
}
public Criteria andTypesNotEqualTo(Integer value) {
addCriterion("TYPES <>", value, "types");
return (Criteria) this;
}
public Criteria andTypesGreaterThan(Integer value) {
addCriterion("TYPES >", value, "types");
return (Criteria) this;
}
public Criteria andTypesGreaterThanOrEqualTo(Integer value) {
addCriterion("TYPES >=", value, "types");
return (Criteria) this;
}
public Criteria andTypesLessThan(Integer value) {
addCriterion("TYPES <", value, "types");
return (Criteria) this;
}
public Criteria andTypesLessThanOrEqualTo(Integer value) {
addCriterion("TYPES <=", value, "types");
return (Criteria) this;
}
public Criteria andTypesIn(List<Integer> values) {
addCriterion("TYPES in", values, "types");
return (Criteria) this;
}
public Criteria andTypesNotIn(List<Integer> values) {
addCriterion("TYPES not in", values, "types");
return (Criteria) this;
}
public Criteria andTypesBetween(Integer value1, Integer value2) {
addCriterion("TYPES between", value1, value2, "types");
return (Criteria) this;
}
public Criteria andTypesNotBetween(Integer value1, Integer value2) {
addCriterion("TYPES not between", value1, value2, "types");
return (Criteria) this;
}
public Criteria andEnableIsNull() {
addCriterion("ENABLE is null");
return (Criteria) this;
}
public Criteria andEnableIsNotNull() {
addCriterion("ENABLE is not null");
return (Criteria) this;
}
public Criteria andEnableEqualTo(Integer value) {
addCriterion("ENABLE =", value, "enable");
return (Criteria) this;
}
public Criteria andEnableNotEqualTo(Integer value) {
addCriterion("ENABLE <>", value, "enable");
return (Criteria) this;
}
public Criteria andEnableGreaterThan(Integer value) {
addCriterion("ENABLE >", value, "enable");
return (Criteria) this;
}
public Criteria andEnableGreaterThanOrEqualTo(Integer value) {
addCriterion("ENABLE >=", value, "enable");
return (Criteria) this;
}
public Criteria andEnableLessThan(Integer value) {
addCriterion("ENABLE <", value, "enable");
return (Criteria) this;
}
public Criteria andEnableLessThanOrEqualTo(Integer value) {
addCriterion("ENABLE <=", value, "enable");
return (Criteria) this;
}
public Criteria andEnableIn(List<Integer> values) {
addCriterion("ENABLE in", values, "enable");
return (Criteria) this;
}
public Criteria andEnableNotIn(List<Integer> values) {
addCriterion("ENABLE not in", values, "enable");
return (Criteria) this;
}
public Criteria andEnableBetween(Integer value1, Integer value2) {
addCriterion("ENABLE between", value1, value2, "enable");
return (Criteria) this;
}
public Criteria andEnableNotBetween(Integer value1, Integer value2) {
addCriterion("ENABLE not between", value1, value2, "enable");
return (Criteria) this;
}
public Criteria andCreatebyIsNull() {
addCriterion("CREATEBY is null");
return (Criteria) this;
}
public Criteria andCreatebyIsNotNull() {
addCriterion("CREATEBY is not null");
return (Criteria) this;
}
public Criteria andCreatebyEqualTo(String value) {
addCriterion("CREATEBY =", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyNotEqualTo(String value) {
addCriterion("CREATEBY <>", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyGreaterThan(String value) {
addCriterion("CREATEBY >", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyGreaterThanOrEqualTo(String value) {
addCriterion("CREATEBY >=", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyLessThan(String value) {
addCriterion("CREATEBY <", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyLessThanOrEqualTo(String value) {
addCriterion("CREATEBY <=", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyLike(String value) {
addCriterion("CREATEBY like", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyNotLike(String value) {
addCriterion("CREATEBY not like", value, "createby");
return (Criteria) this;
}
public Criteria andCreatebyIn(List<String> values) {
addCriterion("CREATEBY in", values, "createby");
return (Criteria) this;
}
public Criteria andCreatebyNotIn(List<String> values) {
addCriterion("CREATEBY not in", values, "createby");
return (Criteria) this;
}
public Criteria andCreatebyBetween(String value1, String value2) {
addCriterion("CREATEBY between", value1, value2, "createby");
return (Criteria) this;
}
public Criteria andCreatebyNotBetween(String value1, String value2) {
addCriterion("CREATEBY not between", value1, value2, "createby");
return (Criteria) this;
}
public Criteria andYearsIsNull() {
addCriterion("YEARS is null");
return (Criteria) this;
}
public Criteria andYearsIsNotNull() {
addCriterion("YEARS is not null");
return (Criteria) this;
}
public Criteria andYearsEqualTo(String value) {
addCriterion("YEARS =", value, "years");
return (Criteria) this;
}
public Criteria andYearsNotEqualTo(String value) {
addCriterion("YEARS <>", value, "years");
return (Criteria) this;
}
public Criteria andYearsGreaterThan(String value) {
addCriterion("YEARS >", value, "years");
return (Criteria) this;
}
public Criteria andYearsGreaterThanOrEqualTo(String value) {
addCriterion("YEARS >=", value, "years");
return (Criteria) this;
}
public Criteria andYearsLessThan(String value) {
addCriterion("YEARS <", value, "years");
return (Criteria) this;
}
public Criteria andYearsLessThanOrEqualTo(String value) {
addCriterion("YEARS <=", value, "years");
return (Criteria) this;
}
public Criteria andYearsLike(String value) {
addCriterion("YEARS like", value, "years");
return (Criteria) this;
}
public Criteria andYearsNotLike(String value) {
addCriterion("YEARS not like", value, "years");
return (Criteria) this;
}
public Criteria andYearsIn(List<String> values) {
addCriterion("YEARS in", values, "years");
return (Criteria) this;
}
public Criteria andYearsNotIn(List<String> values) {
addCriterion("YEARS not in", values, "years");
return (Criteria) this;
}
public Criteria andYearsBetween(String value1, String value2) {
addCriterion("YEARS between", value1, value2, "years");
return (Criteria) this;
}
public Criteria andYearsNotBetween(String value1, String value2) {
addCriterion("YEARS not between", value1, value2, "years");
return (Criteria) this;
}
public Criteria andCreatetimeIsNull() {
addCriterion("CREATETIME is null");
return (Criteria) this;
}
public Criteria andCreatetimeIsNotNull() {
addCriterion("CREATETIME is not null");
return (Criteria) this;
}
public Criteria andCreatetimeEqualTo(Date value) {
addCriterion("CREATETIME =", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotEqualTo(Date value) {
addCriterion("CREATETIME <>", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThan(Date value) {
addCriterion("CREATETIME >", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) {
addCriterion("CREATETIME >=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThan(Date value) {
addCriterion("CREATETIME <", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThanOrEqualTo(Date value) {
addCriterion("CREATETIME <=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeIn(List<Date> values) {
addCriterion("CREATETIME in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotIn(List<Date> values) {
addCriterion("CREATETIME not in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeBetween(Date value1, Date value2) {
addCriterion("CREATETIME between", value1, value2, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotBetween(Date value1, Date value2) {
addCriterion("CREATETIME not between", value1, value2, "createtime");
return (Criteria) this;
}
public Criteria andRemarkIsNull() {
addCriterion("REMARK is null");
return (Criteria) this;
}
public Criteria andRemarkIsNotNull() {
addCriterion("REMARK is not null");
return (Criteria) this;
}
public Criteria andRemarkEqualTo(String value) {
addCriterion("REMARK =", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotEqualTo(String value) {
addCriterion("REMARK <>", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThan(String value) {
addCriterion("REMARK >", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThanOrEqualTo(String value) {
addCriterion("REMARK >=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThan(String value) {
addCriterion("REMARK <", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThanOrEqualTo(String value) {
addCriterion("REMARK <=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLike(String value) {
addCriterion("REMARK like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotLike(String value) {
addCriterion("REMARK not like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkIn(List<String> values) {
addCriterion("REMARK in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotIn(List<String> values) {
addCriterion("REMARK not in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkBetween(String value1, String value2) {
addCriterion("REMARK between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotBetween(String value1, String value2) {
addCriterion("REMARK not between", value1, value2, "remark");
return (Criteria) this;
}
}
/**
user
*
* @mbg.generated do_not_delete_during_merge Mon Jul 06 10:42:37 CST 2020
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
user
*
* @mbg.generated Mon Jul 06 10:42:37 CST 2020
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
example使用
example
//创建
UserExample example=new UserExample();
example.createCriteria().andCreatebyLike("%李%");//设置查询条件
example.setOrderByClause("name desc,types asc");//排序
mapper
一般情况下都会有增删改查方法
@Mapper
public interface FlyDataInfoMapper {
//根据条件求和
long countByExample(UserExample example);
//根据条件删除
int deleteByExample(UserExample example);
//根据主键删除
int deleteByPrimaryKey(String id);
//全字段插入,为null的字段设置为null
int insert(User record);
//根据设置的值插入,为null的字段设置为表定义的默认值
int insertSelective(User record);
//根据条件查询list
List<User> selectByExample(UserExample example);
//根据主键查询list
User selectByPrimaryKey(String deviceStartEndId);
//根据条件更新值(只更新设置了值,值为null的不更新)
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
//根据条件更新值,entity中为null的会设置为null
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
//根据主键更新(只更新设置了值,值为null的不更新)
int updateByPrimaryKeySelective(User record);
//根据主键更新值,entity中为null的会设置为null
int updateByPrimaryKey(User record);
}
在xml中直接编写sql语句
@Update("UPDATE user SET name=${name} WHERE ID = #{id}")
void updateNameById(@Param("name") int name, @Param("id") String id);
xml
- 代码生成的xml
<?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.cc.learn.dao.mysql.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.cc.learn.entity.User">
<id column="ID" jdbcType="VARCHAR" property="id" />
<result column="NAME" jdbcType="VARCHAR" property="name" />
<result column="TYPES" jdbcType="INTEGER" property="types" />
<result column="ENABLE" jdbcType="INTEGER" property="enable" />
<result column="CREATEBY" jdbcType="VARCHAR" property="createby" />
<result column="YEARS" jdbcType="VARCHAR" property="years" />
<result column="CREATETIME" jdbcType="TIMESTAMP" property="createtime" />
<result column="REMARK" jdbcType="VARCHAR" property="remark" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
ID, NAME, TYPES, ENABLE, CREATEBY, YEARS, CREATETIME, REMARK
</sql>
<select id="selectByExample" parameterType="com.cc.learn.entity.UserExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where ID = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from user
where ID = #{id,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="com.cc.learn.entity.UserExample">
delete from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.cc.learn.entity.User">
insert into user (ID, NAME, TYPES,
ENABLE, CREATEBY, YEARS,
CREATETIME, REMARK)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{types,jdbcType=INTEGER},
#{enable,jdbcType=INTEGER}, #{createby,jdbcType=VARCHAR}, #{years,jdbcType=VARCHAR},
#{createtime,jdbcType=TIMESTAMP}, #{remark,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.cc.learn.entity.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
ID,
</if>
<if test="name != null">
NAME,
</if>
<if test="types != null">
TYPES,
</if>
<if test="enable != null">
ENABLE,
</if>
<if test="createby != null">
CREATEBY,
</if>
<if test="years != null">
YEARS,
</if>
<if test="createtime != null">
CREATETIME,
</if>
<if test="remark != null">
REMARK,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="types != null">
#{types,jdbcType=INTEGER},
</if>
<if test="enable != null">
#{enable,jdbcType=INTEGER},
</if>
<if test="createby != null">
#{createby,jdbcType=VARCHAR},
</if>
<if test="years != null">
#{years,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
#{createtime,jdbcType=TIMESTAMP},
</if>
<if test="remark != null">
#{remark,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.cc.learn.entity.UserExample" resultType="java.lang.Long">
select count(*) from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update user
<set>
<if test="record.id != null">
ID = #{record.id,jdbcType=VARCHAR},
</if>
<if test="record.name != null">
NAME = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.types != null">
TYPES = #{record.types,jdbcType=INTEGER},
</if>
<if test="record.enable != null">
ENABLE = #{record.enable,jdbcType=INTEGER},
</if>
<if test="record.createby != null">
CREATEBY = #{record.createby,jdbcType=VARCHAR},
</if>
<if test="record.years != null">
YEARS = #{record.years,jdbcType=VARCHAR},
</if>
<if test="record.createtime != null">
CREATETIME = #{record.createtime,jdbcType=TIMESTAMP},
</if>
<if test="record.remark != null">
REMARK = #{record.remark,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update user
set ID = #{record.id,jdbcType=VARCHAR},
NAME = #{record.name,jdbcType=VARCHAR},
TYPES = #{record.types,jdbcType=INTEGER},
ENABLE = #{record.enable,jdbcType=INTEGER},
CREATEBY = #{record.createby,jdbcType=VARCHAR},
YEARS = #{record.years,jdbcType=VARCHAR},
CREATETIME = #{record.createtime,jdbcType=TIMESTAMP},
REMARK = #{record.remark,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.cc.learn.entity.User">
update user
<set>
<if test="name != null">
NAME = #{name,jdbcType=VARCHAR},
</if>
<if test="types != null">
TYPES = #{types,jdbcType=INTEGER},
</if>
<if test="enable != null">
ENABLE = #{enable,jdbcType=INTEGER},
</if>
<if test="createby != null">
CREATEBY = #{createby,jdbcType=VARCHAR},
</if>
<if test="years != null">
YEARS = #{years,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
CREATETIME = #{createtime,jdbcType=TIMESTAMP},
</if>
<if test="remark != null">
REMARK = #{remark,jdbcType=VARCHAR},
</if>
</set>
where ID = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.cc.learn.entity.User">
update user
set NAME = #{name,jdbcType=VARCHAR},
TYPES = #{types,jdbcType=INTEGER},
ENABLE = #{enable,jdbcType=INTEGER},
CREATEBY = #{createby,jdbcType=VARCHAR},
YEARS = #{years,jdbcType=VARCHAR},
CREATETIME = #{createtime,jdbcType=TIMESTAMP},
REMARK = #{remark,jdbcType=VARCHAR}
where ID = #{id,jdbcType=VARCHAR}
</update>
</mapper>
分页
mybatis的分页功能,在需要分页的sql查询之前设置
PageHelper.startPage(pageNum, pageSize);
进行对它下面的第一条sql语句进行分页
PageHelper.startPage(pageNum, pageSize);// 分页
List<T> list = dao.selectByExample(entity);
PageInfo<T> pageInfo = new PageInfo<T>(list, 5); // 5代表生成5导航页
MyBatis-plus
MyBatis-plus是一款MyBatis的增强工具,在MyBatis 的基础上只做增强不做改变。其是国内团队苞米豆在MyBatis基础上开发的增强框架,扩展了一些功能,以提高效率。引入 Mybatis-Plus 不会对现有的 Mybatis 构架产生任何影响,而且 MyBatis-plus 支持所有 Mybatis 原生的特性
- 依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring 。
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作 。
- 预防Sql注入:内置 Sql 注入剥离器,有效预防Sql注入攻击 。
- 通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求 。
- 多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题 。
- 支持热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
- 支持ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作
- 支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码(生成自定义文件,避免开发重复代码),支持模板引擎、有超多自定义配置等。
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )。
- 支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词 。
- 内置分页插件:基于 Mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询。
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询 。
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作。
- 默认将实体类的类名查找数据库中的表,使用@TableName(value="table1")注解指定表名,@TableId指定表主键,若字段与表中字段名保持一致可不加注解。
mybatis plus使用
依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
配置
mybatis-plus:
# xml(此时xml文件在resources/mapper文件夹中)
mapper-locations: classpath:mappings/**/*.xml #自动扫描mapper.xml文件,支持通配符
# 实体扫描,多个package用逗号或者分号分隔(entity路径)
type-aliases-package: com.cc.learn.entity
configuration:
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 驼峰形式处理entity
map-underscore-to-camel-case: true
- entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("user")
public class User {
/**
* ID
*/
@TableId("ID")
private String id;
/**
* NAME
*/
@TableField("NAME")
private String name;
/**
* TYPES
*/
@TableField("TYPES")
private Integer types;
/**
* ENABLE
*/
@TableField("ENABLE")
private Integer enable;
/**
* CREATEBY
*/
@TableField("CREATEBY")
private String createby;
/**
* YEARS
*/
@TableField("YEARS")
private String years;
/**
* CREATETIME
*/
@TableField("CREATETIME")
private LocalDateTime createtime;
/**
* REMARK
*/
@TableField("REMARK")
private String remark;
public static final String ID = "ID";
public static final String NAME = "NAME";
public static final String TYPES = "TYPES";
public static final String ENABLE = "ENABLE";
public static final String CREATEBY = "CREATEBY";
public static final String YEARS = "YEARS";
public static final String CREATETIME = "CREATETIME";
public static final String REMARK = "REMARK";
}
拼接查询条件
mybatis plus拼接查询条件基本上可以编写所有的接口,
public Wrapper<User> getQueryByEntity(PageReq entity) {
QueryWrapper<User> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(entity.getName())) {
//设置like
query.like(User.NAME, entity.getName());
}
if (StringUtils.isNotBlank(entity.getParam())) {
//设置查询参数
query.select(entity.getParam());
}
//设置where中的(),一般在有or的时候使用
query.and(wapper->wapper.eq(User.NAME, entity.getName()).or().eq(User.REMARK, entity.getName()));
query.orderByDesc(User.STATES);
query.orderByAsc(User.ID);
return query;
}
比如
QueryWrapper<User> userInfoQueryWrapper=new QueryWrapper<>();
//设置select的查询字段
userInfoQueryWrapper.select(User.ID, User.NAME, User.USERID, User.ATT_DEPT_ID, User.AVATAR,"DATE_FORMAT(birthday,'"+req.getStartDate().getYear()+"-%m-%d') birthday");
//设置where条件
userInfoQueryWrapper.ne(User.STATUS, 9);
userInfoQueryWrapper.orderByAsc(User.BIRTHDAY, User.NAME);
//设置having条件
userInfoQueryWrapper.having("birthday >={0} and birthday <={1}",req.getStartDate(),req.getEndDate());
//查询
List<User> list = list(userInfoQueryWrapper);
//SELECT id,name,userid,att_dept_id,avatar,DATE_FORMAT(birthday,'2020-%m-%d') birthday FROM user WHERE status <> 9 HAVING birthday >='2020-01-12' and birthday <='2020-06-01' ORDER BY birthday ASC , name ASC
比如:
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//设置update的set
updateWrapper.set(User.NAME, entity.getName());
updateWrapper.set(User.TYPES, entity.getTypes());
updateWrapper.set(User.PLAN_DETAIL_ID, entity.getPlanDetailId());
updateWrapper.set(User.ADD_ID, entity.getAddId());
//设置where条件
updateWrapper.eq(User.ID, entity.getId());
update(updateWrapper);
有很多方法:
查询条件的拼接在mybatis plus的官网讲解的很详细;
service:
mybatis plus提供了ServiceImpl
和IService
,里面都大部分的常用方法
IService
这是mybatis plus默认提供的方法,打开mybatis plus源码即可看到
public interface IService<T> {
/**
* 插入一条记录(选择字段,策略插入)
*
* @param entity 实体对象
*/
boolean save(T entity);
/**
* 插入(批量)
*
* @param entityList 实体对象集合
*/
@Transactional(rollbackFor = Exception.class)
default boolean saveBatch(Collection<T> entityList) {
return saveBatch(entityList, 1000);
}
/**
* 插入(批量)
*
* @param entityList 实体对象集合
* @param batchSize 插入批次数量
*/
boolean saveBatch(Collection<T> entityList, int batchSize);
/**
* 批量修改插入
*
* @param entityList 实体对象集合
*/
@Transactional(rollbackFor = Exception.class)
default boolean saveOrUpdateBatch(Collection<T> entityList) {
return saveOrUpdateBatch(entityList, 1000);
}
/**
* 批量修改插入
*
* @param entityList 实体对象集合
* @param batchSize 每次的数量
*/
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
boolean removeById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
boolean removeByMap(Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param queryWrapper 实体包装类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
boolean remove(Wrapper<T> queryWrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表
*/
boolean removeByIds(Collection<? extends Serializable> idList);
/**
* 根据 ID 选择修改
*
* @param entity 实体对象
*/
boolean updateById(T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象
* @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);
/**
* 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
*
* @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
default boolean update(Wrapper<T> updateWrapper) {
return update(null, updateWrapper);
}
/**
* 根据ID 批量更新
*
* @param entityList 实体对象集合
*/
@Transactional(rollbackFor = Exception.class)
default boolean updateBatchById(Collection<T> entityList) {
return updateBatchById(entityList, 1000);
}
/**
* 根据ID 批量更新
*
* @param entityList 实体对象集合
* @param batchSize 更新批次数量
*/
boolean updateBatchById(Collection<T> entityList, int batchSize);
/**
* TableId 注解存在更新记录,否插入一条记录
*
* @param entity 实体对象
*/
boolean saveOrUpdate(T entity);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T getById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表
*/
Collection<T> listByIds(Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
Collection<T> listByMap(Map<String, Object> columnMap);
/**
* 根据 Wrapper,查询一条记录 <br/>
* <p>结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")</p>
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
default T getOne(Wrapper<T> queryWrapper) {
return getOne(queryWrapper, true);
}
/**
* 根据 Wrapper,查询一条记录
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
* @param throwEx 有多个 result 是否抛出异常
*/
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
/**
* 根据 Wrapper,查询一条记录
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
Map<String, Object> getMap(Wrapper<T> queryWrapper);
/**
* 根据 Wrapper,查询一条记录
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
* @param mapper 转换函数
*/
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
int count(Wrapper<T> queryWrapper);
/**
* 查询总记录数
*
* @see Wrappers#emptyWrapper()
*/
default int count() {
return count(Wrappers.emptyWrapper());
}
/**
* 查询列表
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
List<T> list(Wrapper<T> queryWrapper);
/**
* 查询所有
*
* @see Wrappers#emptyWrapper()
*/
default List<T> list() {
return list(Wrappers.emptyWrapper());
}
/**
* 翻页查询
*
* @param page 翻页对象
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
/**
* 无条件翻页查询
*
* @param page 翻页对象
* @see Wrappers#emptyWrapper()
*/
default IPage<T> page(IPage<T> page) {
return page(page, Wrappers.emptyWrapper());
}
/**
* 查询列表
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
/**
* 查询所有列表
*
* @see Wrappers#emptyWrapper()
*/
default List<Map<String, Object>> listMaps() {
return listMaps(Wrappers.emptyWrapper());
}
/**
* 查询全部记录
*/
default List<Object> listObjs() {
return listObjs(Function.identity());
}
/**
* 查询全部记录
*
* @param mapper 转换函数
*/
default <V> List<V> listObjs(Function<? super Object, V> mapper) {
return listObjs(Wrappers.emptyWrapper(), mapper);
}
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
default List<Object> listObjs(Wrapper<T> queryWrapper) {
return listObjs(queryWrapper, Function.identity());
}
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
* @param mapper 转换函数
*/
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
/**
* 翻页查询
*
* @param page 翻页对象
* @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
/**
* 无条件翻页查询
*
* @param page 翻页对象
* @see Wrappers#emptyWrapper()
*/
default IPage<Map<String, Object>> pageMaps(IPage<T> page) {
return pageMaps(page, Wrappers.emptyWrapper());
}
/**
* 获取对应 entity 的 BaseMapper
*
* @return BaseMapper
*/
BaseMapper<T> getBaseMapper();
/**
* 以下的方法使用介绍:
*
* 一. 名称介绍
* 1. 方法名带有 query 的为对数据的查询操作, 方法名带有 update 的为对数据的修改操作
* 2. 方法名带有 lambda 的为内部方法入参 column 支持函数式的
*
* 二. 支持介绍
* 1. 方法名带有 query 的支持以 {@link ChainQuery} 内部的方法名结尾进行数据查询操作
* 2. 方法名带有 update 的支持以 {@link ChainUpdate} 内部的方法名为结尾进行数据修改操作
*
* 三. 使用示例,只用不带 lambda 的方法各展示一个例子,其他类推
* 1. 根据条件获取一条数据: `query().eq("column", value).one()`
* 2. 根据条件删除一条数据: `update().eq("column", value).remove()`
*
*/
/**
* 链式查询 普通
*
* @return QueryWrapper 的包装类
*/
default QueryChainWrapper<T> query() {
return new QueryChainWrapper<>(getBaseMapper());
}
/**
* 链式查询 lambda 式
* <p>注意:不支持 Kotlin </p>
*
* @return LambdaQueryWrapper 的包装类
*/
default LambdaQueryChainWrapper<T> lambdaQuery() {
return new LambdaQueryChainWrapper<>(getBaseMapper());
}
/**
* 链式更改 普通
*
* @return UpdateWrapper 的包装类
*/
default UpdateChainWrapper<T> update() {
return new UpdateChainWrapper<>(getBaseMapper());
}
/**
* 链式更改 lambda 式
* <p>注意:不支持 Kotlin </p>
*
* @return LambdaUpdateWrapper 的包装类
*/
default LambdaUpdateChainWrapper<T> lambdaUpdate() {
return new LambdaUpdateChainWrapper<>(getBaseMapper());
}
}
- service需要继承
ServiceImpl
其中,在service层有默认的
baseMapper
,是ServiceImpl第一个参数对应的mapper
@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper, User> implements UserServiceInter {
}
- serviceInter
public interface UserServiceInter extends IService<UserRules> {
}
但是接口层可以省略
@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper, User> {}
mapper:
需要继承BaseMapper
,默认提供了常用的方法
@Mapper
public interface AttendanceRulesMapper extends BaseMapper<AttendanceRules> {
}
BaseMapper默认方法
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
xml
xml中,基础定义和mybatis一样,但是mybatis plus就不需要那一堆的example的代码了
<?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.cc.learn.mapper.UserMapper">
</mapper>
分页
IPage<User> page = service.page(new Page<>(pagenum, pagesize), queryWrapper);
参考: