åå¨å¼å§:ä¸ä¸ªæ¬ç ç¨åºåçéç¼è®°å½
MyBatis-Plusï¼ç®ç§° MPï¼æ¯ä¸ä¸ª MyBatis çå¢å¼ºå·¥å ·ï¼å¨ MyBatis çåºç¡ä¸åªåå¢å¼ºä¸åæ¹åï¼ä¸ºç®åå¼åãæé«æçèçã
å®ç½å°åï¼MyBatis-Plus
ä¹ååäºMyBatisç使ç¨ï¼ä¸¤è 对æ¯èµ·æ¥ï¼MyBatis-Plus对æ¯Mybatisç¨èµ·æ¥æ¯æ¯è¾æ¹ä¾¿ï¼å¾å¤åºæ¬çæä½é½å°è£ å¾å¾å¥½ï¼è¿æèªå®ä¹èªå¨çæåºæ¬ä»£ç çåè½ï¼ä¸ç¯æç« ä¼è®²å°
æç« ç®å½
- ä¸ãå建æ°æ®åº
- äºãå建ä¸ä¸ªSpringBoot项ç®
-
- 1ãMybatis-Plusçä¾èµ
- 2ãå¨ Spring Boot å¯å¨ç±»ä¸æ·»å @MapperScan 注解ï¼æ«æ Mapper æ件夹ï¼
- 3ãæ°æ®æºé ç½®
- ä¸ãMyBatis-Plus
-
- 1ãMybatis-Plus注解
- 2ãæ¡ä»¶æé å¨
-
- 1ãeq
- 2ãne
- 3ãgt
- 4ãge
- 5ãlt
- 6ãle
- 3ãCRUD æ¥å£
-
- 1ãsave
- 2ãremove
- 3ãupdate
- 4ãgetById
- 5ãlist
- 6ãpage
- 7ãcount
- åãå®æ代ç
ä¸ãå建æ°æ®åº
CREATE TABLE `tb_user_dat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'å§å',
`sex` int(11) DEFAULT NULL COMMENT 'æ§å« 1:ç· 2:女',
`age` int(11) DEFAULT NULL COMMENT 'å¹´é¾',
`create_time` datetime DEFAULT NULL COMMENT 'å建æ¶é´',
`create_user` int(11) DEFAULT NULL COMMENT 'å建人',
`update_time` datetime DEFAULT NULL COMMENT 'ä¿®æ¹æ¶é´',
`update_user` int(11) DEFAULT NULL COMMENT 'ä¿®æ¹äºº',
`is_delete` tinyint(1) DEFAULT '1' COMMENT 'æ¯å¦å·²å é¤ 1:æ¯ 0:å¦',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
äºãå建ä¸ä¸ªSpringBoot项ç®
å¯ä»¥çä¹åçæç« ï¼SpringBoot项ç®å¿«éæ建
项ç®ç»æï¼
1ãMybatis-Plusçä¾èµ
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
æ´ä½ä¾èµ
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2ãå¨ Spring Boot å¯å¨ç±»ä¸æ·»å @MapperScan 注解ï¼æ«æ Mapper æ件夹ï¼
package com.cn.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author demo
*/
@SpringBootApplication
@MapperScan("com.cn.mybatisplus.mapper")
public class MybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusDemoApplication.class, args);
}
}
3ãæ°æ®æºé ç½®
application.yml
server:
port: 8080 #端å£å·
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf-8 #æ°æ®åºurl
username: root #æ°æ®åºç¨æ·å
password: admin #æ°æ®åºå¯ç
driver-class-name: com.mysql.jdbc.Driver
ä¸ãMyBatis-Plus
ç¼åå®ä½ç±»TbUserDat.java
ä¹å¯ä»¥ä½¿ç¨Ideaèªå¸¦çdatabaseçæå®ä½ç±»
é¾æ¥ï¼IDEAä¸é®çæ表å段ååºæ¬ä»£ç
TbUserDat.java
package com.cn.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.io.Serializable;
/**
* (TbUserDat)å®ä½ç±»
* * @author makejava
* @since 2020-05-20 15:10:56
*/
@Data
public class TbUserDat implements Serializable {
private static final long serialVersionUID = 299266960321958614L;
/**
* id
*
* */
@TableId(type = IdType.AUTO)
private Integer id;
/**
* å§å
*/
private String name;
/**
* æ§å« 1:ç· 2:女
*/
private Integer sex;
/**
* å¹´é¾
*/
private Integer age;
/**
* å建æ¶é´
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "create_date", fill = FieldFill.INSERT)
private Date createTime;
/**
* å建人
*/
private Integer createUser;
/**
* ä¿®æ¹æ¶é´
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "update_date", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* ä¿®æ¹äºº
*/
private Integer updateUser;
/**
* æ¯å¦å·²å é¤ 1:æ¯ 0:å¦
*/
@TableLogic
private Boolean isDelete;
}
1ãMybatis-Plus注解
ä¸é¢ç¨å°å 个常ç¨çMybatis-plus注解
- @TableId
æè¿°ï¼ä¸»é®æ³¨è§£
- @TableField
@TableField(value = "create_date", fill = FieldFill.INSERT)
æè¿°ï¼åªæè¿è¡æ°å¢æä½æä¼è¿è¡æ´æ°è¿ä¸ªå段ï¼ç¨äºå建æ¶é´ç±»å段
@TableField(value = "update_date", fill = FieldFill.INSERT_UPDATE)
æè¿°ï¼åªæè¿è¡æ°å¢æä½æä¼è¿è¡æ´æ°è¿ä¸ªå段ï¼ç¨äºä¿®æ¹æ¶é´ç±»å段
主è¦å¨äºfillç使ç¨
- @TableLogic
éè¦å¨application.ymlä¸å å ¥mybatisé ç½®
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag #å
¨å±é»è¾å é¤åæ®µå¼ 3.3.0å¼å§æ¯æï¼è¯¦æ
çä¸é¢ã
logic-delete-value: 1 # é»è¾å·²å é¤å¼(é»è®¤ä¸º 1)
logic-not-delete-value: 0 # é»è¾æªå é¤å¼(é»è®¤ä¸º 0)
ç¶åå¨å®ä½ç±»ä¸ç©çå é¤å段ä¸å ä¸@TableLogic注解
æ³äºè§£æ´å¤æ³¨è§£å¯ä»¥å»å®ç½çææ¡£
2ãæ¡ä»¶æé å¨
1ãeq
- ç¸å½äº=
- ä¾: eq(ânameâ, âå°ç½â)â>name = âå°ç½â
2ãne
- ä¸çäº !=
- ä¾: ne(ânameâ, âå°ç½â)â>name != âå°ç½â
3ãgt
- å¤§äº >
- ä¾: gt(âageâ, 18)â>age > 18
4ãge
- 大äºçäº >=
- ä¾: ge(âageâ, 18)â>age >= 18
5ãlt
- å°äº <
- ä¾: lt(âageâ, 18)â>age < 18
6ãle
- å°äºçäº <=
- ä¾: le(âageâ, 18)â>age <= 18
3ãCRUD æ¥å£
å¢å æ¹æ¥é½æå¤ç§ä¸åçæ¹å¼ï¼è¿éåªå举常ç¨ç
1ãsave
æè¿°ï¼ä¿å
// æå
¥ä¸æ¡è®°å½ï¼éæ©å段ï¼çç¥æå
¥ï¼
boolean save(T entity);
2ãremove
æè¿°ï¼å é¤ï¼æé ç½®ç©çå é¤å°±æ¯ç©çå é¤ä¸ä¼å é¤æ°æ®
// æ ¹æ® entity æ¡ä»¶ï¼å é¤è®°å½
boolean remove(Wrapper<T> queryWrapper);
3ãupdate
æè¿°ï¼ä¿®æ¹
// æ ¹æ® whereEntity æ¡ä»¶ï¼æ´æ°è®°å½
boolean update(T entity, Wrapper<T> updateWrapper);
4ãgetById
æè¿°ï¼æ ¹æ®idæ¥è¯¢è¯¦æ
// æ ¹æ® ID æ¥è¯¢
T getById(Serializable id);
5ãlist
æè¿°ï¼æ¥è¯¢å表
// æ¥è¯¢ææ
List<T> list();
6ãpage
æè¿°ï¼å页æ¥è¯¢
// æ æ¡ä»¶ç¿»é¡µæ¥è¯¢
IPage<T> page(IPage<T> page);
7ãcount
æè¿°ï¼æ¥è¯¢æ»æ¡æ°
// æ¥è¯¢æ»è®°å½æ°
int count();
åãå®æ代ç
å页æ件ï¼
å¯å¨ç±»é ç½®å页æ件é ç½®ï¼å ä¸æ³¨è§£
@EnableTransactionManagement
@Configuration
package com.cn.mybatisplus;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author demo
*/
@SpringBootApplication
@EnableTransactionManagement
@Configuration
@MapperScan("com.cn.mybatisplus.mapper")
public class MybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusDemoApplication.class, args);
}
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请æ±ç页é¢å¤§äºæ大页åæä½ï¼ trueè°åå°é¦é¡µï¼false 继ç»è¯·æ± é»è®¤false
// paginationInterceptor.setOverflow(false);
// 设置æ大å页éå¶æ°éï¼é»è®¤ 500 æ¡ï¼-1 ä¸åéå¶
// paginationInterceptor.setLimit(500);
// å¼å¯ count ç join ä¼å,åªé对é¨å left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
serviceå®ç°ç±»æ¹æ³
@Override
public IPage<TbUserDat> getUserPageList(Integer pageNum, Integer pageSize) {
//å页
Page<TbUserDat> page = new Page<>(pageNum,pageSize);
//å å
¥çéæ¡ä»¶
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", false);
Page<TbUserDat> tbUserDatPage = page(page, queryWrapper);
return tbUserDatPage;
}
åºæ¬ä¸å¡å ¨é¨ä»£ç ï¼
controller:
package com.cn.mybatisplus.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cn.mybatisplus.entity.TbUserDat;
import com.cn.mybatisplus.service.MybatisPlusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Author: demo
* @Date: 2020-05-20 15:02
*/
@RestController
public class MybatisPlusController {
@Autowired
private MybatisPlusService mybatisPlusService;
/**
* æ¥è¯¢ç¨æ·å表
*
* @return
* */
@GetMapping("/user")
public List<TbUserDat> getUserList() {
return mybatisPlusService.getUserList();
}
/**
* å页æ¥è¯¢ç¨æ·å表
*
* @param pageNum
* @param pageSize
* @return
* */
@GetMapping("/user/page")
public IPage<TbUserDat> getUserPageList(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
return mybatisPlusService.getUserPageList(pageNum, pageSize);
}
/**
* æ ¹æ®idæ¥è¯¢ç¨æ·
*
* @param id
* @return
*/
@GetMapping("/user/{id}")
public TbUserDat getUserById(@PathVariable("id") Integer id) {
if (id == null) {
return null;
}
return mybatisPlusService.getUserById(id);
}
/**
* æ°å¢ç¨æ·
*
* @param tbUserDat
* @return
* */
@PostMapping("/user")
public Integer addUser(@RequestBody TbUserDat tbUserDat) {
return mybatisPlusService.addUser(tbUserDat);
}
/**
* ä¿®æ¹ç¨æ·
*
* @param tbUserDat
* @return
* */
@PatchMapping("/user")
public Integer updateUser(@RequestBody TbUserDat tbUserDat) {
return mybatisPlusService.updateUser(tbUserDat);
}
/**
* æ ¹æ®ç¨æ·idå é¤ç¨æ·
*
* @param id
* @return
* */
@DeleteMapping("/user/{id}")
public Integer deleteUser(@PathVariable("id") Integer id) {
return mybatisPlusService.deleteUser(id);
}
}
service:
package com.cn.mybatisplus.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cn.mybatisplus.entity.TbUserDat;
import java.util.List;
/**
* @Author: demo
* @Date: 2020-05-20 15:01
*/
public interface MybatisPlusService {
/**
* æ¥è¯¢ç¨æ·å表
*
* @return
* */
List<TbUserDat> getUserList();
/**
* å页æ¥è¯¢ç¨æ·å表
*
* @param pageNum
* @param pageSize
* @return
* */
IPage<TbUserDat> getUserPageList(Integer pageNum, Integer pageSize);
/**
* æ ¹æ®idæ¥è¯¢ç¨æ·
*
* @param id
* @return
* */
TbUserDat getUserById(Integer id);
/**
* æ°å¢ç¨æ·
*
* @param tbUserDat
* @return
* */
Integer addUser(TbUserDat tbUserDat);
/**
* ä¿®æ¹ç¨æ·
*
* @param tbUserDat
* @return
* */
Integer updateUser(TbUserDat tbUserDat);
/**
* æ ¹æ®ç¨æ·idå é¤ç¨æ·
*
* @param id
* @return
* */
Integer deleteUser(Integer id);
}
serviceImpl:
package com.cn.mybatisplus.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.mybatisplus.entity.TbUserDat;
import com.cn.mybatisplus.mapper.MybatisPlusMapper;
import com.cn.mybatisplus.service.MybatisPlusService;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @Author: demo
* @Date: 2020-05-20 15:02
*/
@Service
public class MybatisPlusServiceImpl extends ServiceImpl<MybatisPlusMapper, TbUserDat> implements MybatisPlusService {
@Override
public List<TbUserDat> getUserList() {
List<TbUserDat> list = list();
return list;
}
@Override
public IPage<TbUserDat> getUserPageList(Integer pageNum, Integer pageSize) {
//å页
Page<TbUserDat> page = new Page<>(pageNum,pageSize);
//å å
¥çéæ¡ä»¶
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", false);
Page<TbUserDat> tbUserDatPage = page(page, queryWrapper);
return tbUserDatPage;
}
@Override
public TbUserDat getUserById(Integer id) {
//ç´æ¥è°ç¨å°è£
çæ¹æ³
TbUserDat tbUserDat = getById(id);
return tbUserDat;
}
@Override
public Integer addUser(TbUserDat tbUserDat) {
tbUserDat.setCreateTime(new Date());
tbUserDat.setUpdateTime(new Date());
save(tbUserDat);
return tbUserDat.getId();
}
@Override
public Integer updateUser(TbUserDat tbUserDat) {
tbUserDat.setUpdateTime(new Date());
//两ç§æ¹å¼
//第ä¸ç§ï¼æ ¹æ®idä¿®æ¹,éè¦æ ¡éªidä¸è½ä¸ºç©º
if (tbUserDat.getId() == null) {
return -1;
}
updateById(tbUserDat);
//第äºç§ï¼æ ¹æ®æ¡ä»¶è¿è¡ä¿®æ¹,è¿ééè¦æ³¨æeqåé¢çå¼éè¦åæ°æ®åºçå段ä¸è´ï¼ä¸æ¯å®ä½ç±»çå段åï¼æ³¨æï¼æ³¨æï¼æ³¨æ
QueryWrapper<TbUserDat> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", tbUserDat.getId());
update(tbUserDat, queryWrapper);
return tbUserDat.getId();
}
@Override
public Integer deleteUser(Integer id) {
//æ ¹æ®idå é¤id
removeById(id);
//æ ¹æ®æ¡ä»¶å é¤id
QueryWrapper<TbUserDat> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", id);
remove(queryWrapper);
return id;
}
}
ä¸ç¯æç« ä¼ä»ç»MybatisPlus代ç çæå¨
Over