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);
參考:
