Mvnw 配置
//mysql驅動
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
//mabatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
application.yml 配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
啟動類上面加MapperScan
@MapperScan("mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
數(shù)據(jù)類
package entity;
public class User
{
private long id;
private String name;
private Integer age;
private String email;
//省略Get Set方法
}
接口類
package mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import entity.User;
public interface UserMapper extends BaseMapper<User> {
}
測試類
package com.example.demo;
import entity.User;
import mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
//查詢
@Test
public void selectData()
{
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
//更新
@Test
void UpdateData()
{
User user=new User();
user.setId(6);
user.setName("zs更新123");
int rows=userMapper.updateById(user);
System.out.println("update的"+rows);
}
//插入
@Test
void testInsert(){
User user=new User();
user.setName("zhangxu12345111");
user.setAge(4);
user.setEmail("26195888@qq.com");
int result=userMapper.insert(user);
System.out.println(result);
}
//刪除通過id
@Test
void testDeleteById()
{
int rows=userMapper.deleteById(7);
System.out.println("delete"+rows);
}
//刪除通過Map
@Test
void testDeleteByMap(){
Map<String,Object> map=new HashMap<>();
map.put("age",11);
int rows=userMapper.deleteByMap(map);
System.out.println("update的"+rows);
}
}
配置輸出日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
自動填充時間
1碰酝、在數(shù)據(jù)庫創(chuàng)建字段 create_time 創(chuàng)建時間 update_time 更新時間
2吼鱼、實體類字段屬性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3糙及、編寫處理器來處理注解 handle.MyMetaObjectHandle.class
package com.zhang.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandle implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(),metaObject);
this.setFieldValByName("updateTime", new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject)
{
this.setFieldValByName("updateTime", new Date(),metaObject);
}
}
樂觀鎖
1让腹、在數(shù)據(jù)庫增加version字段
2啃勉、在實體類的字段上加上@Version
注解
@Version
private Integer version;
3罕拂、添加配置類加上注解 config.MybatisPlusConfig.class
package com.zhang.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.zhang.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
查詢操作
//單個用戶查詢
@Test
void testSelectById(){
User user = userMapper.selectById(1);
System.out.println(user);
}
//多個用戶查詢
@Test
void testSelectBybatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
System.out.println(users);
}
//條件查詢使用map
@Test
void testSelectBybatchIds(){
HashMap<String, Object> map = new HashMap<>();
map.put("age",11);
List<User> users = userMapper.selectByMap(map);
System.out.println(users);
}
分頁查詢
1仰剿、再配置類里面添加配置插件 MybatisPlusConfig
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
2卧须、測試查詢
//測試分頁查詢
@Test
void testPage(){
Page<User> page = new Page<>(1,3);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
Wrapper應用
原文鏈接:https://blog.csdn.net/weixin_44870909/article/details/108761753
1. ge另绩、gt、le花嘶、lt笋籽、isNull、isNotNull
ge 大于等于
gt 大于
le 小于等于
lt 小于
isNull 字段 IS NULL (該字段為空)
isNotNull 字段 IS NOT NULL (該字段不為空)
-
下面示例是邏輯刪除 而不是物理刪除
@Test public void testDelete() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper .isNull("name") .ge("age", 12) .isNotNull("email"); int result = userMapper.delete(queryWrapper); System.out.println("delete return count = " + result); }
2. eq椭员、ne
- eq 等于
- ne 不等于
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "Tom");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
3. between车海、notBetween
between BETWEEN 值1 AND 值2
notBetween NOT BETWEEN 值1 AND 值2
-
包含大小邊界
@Test public void testSelectCount() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.between("age", 20, 30); Integer count = userMapper.selectCount(queryWrapper); System.out.println(count); }
4、allEq
- allEq 全部相等
@Test
public void testSelectList() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("name", "Jack");
map.put("age", 20);
queryWrapper.allEq(map);
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
5隘击、like侍芝、notLike、likeLeft埋同、likeRight
- like LIKE ‘%值%’
- notLike NOT LIKE ‘%值%’
- likeLeft LIKE ‘%值’
- likeRight LIKE ‘值%’
- selectMaps返回Map集合列表
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.notLike("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
maps.forEach(System.out::println);
}
6州叠、in、notIn凶赁、inSql咧栗、notInSql、exists虱肄、notExists
in 字段 IN (v0, v1, v2, …)
notIn 字段 NOT IN(v0, v1, v2, …)
inSql 字段 IN (SQL語句)
notInSql 字段 NOT IN (SQL語句)
exists 拼接 EXISTS (SQL語句)
notExists 拼接 NOT EXISTS (SQL語句)
in致板、notIn:
notIn(“age”,{1,2,3})—>age not in (1,2,3)
notIn(“age”, 1, 2, 3)—>age not in (1,2,3)
inSql、notinSql:可以實現(xiàn)子查詢
例: inSql(“age”, “1,2,3,4,5,6”)—>age in (1,2,3,4,5,6)
例: inSql(“id”, “select id from table where id < 3”)—>id in (select id from table where id < 3)
@Test
public void testSelectObjs() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//queryWrapper.in("id", 1, 2, 3);
queryWrapper.inSql("id", "select id from user where id < 3");
List<Object> objects = userMapper.selectObjs(queryWrapper);//返回值是Object列表
objects.forEach(System.out::println);
}
7. or咏窿、and
-
注意:這里使用的是 UpdateWrapper
不調用or則默認為使用 and 連
@Test
public void testUpdate1() {
//修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
//修改條件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.or()
.between("age", 20, 30);
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}
8. 嵌套or斟或、嵌套and
這里使用了lambda表達式,or中的表達式最后翻譯成sql時會被加上圓括號
@Test
public void testUpdate2() {
//修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
//修改條件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.or(i -> i.eq("name", "李白").ne("age", 20));
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}