首页 > 其他分享 >MybatisPlus

MybatisPlus

时间:2023-07-16 09:13:15浏览次数:31  
标签:mybatisplus System user println import com MybatisPlus

目录

config

MybatisPlusConfig.java

package com.bijian.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
//可以将主类中的注解移到此处
@MapperScan("com.bijian.mybatisplus.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

enums

SexEnum.java

package com.bijian.mybatisplus.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

@Getter
public enum SexEnum {
    MALE(1, "男"),
    FEMALE(2, "女");

    @EnumValue // 将注解所标识的属性的值存储到数据库中
    private Integer sex;
    private String sexName;

    SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }
}

java/mapper

ProductMapper.java

package com.bijian.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bijian.mybatisplus.pojo.Product;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductMapper extends BaseMapper<Product> {

}

UserMapper.java

package com.bijian.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bijian.mybatisplus.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public interface UserMapper extends BaseMapper<User> {
    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String,Object> selectMapById(Long id);

    /**
     * 通过年龄查询用户信息并分页
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
     * @param age
     * @return
     */
    Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);

}

pojo

Product.java

package com.bijian.mybatisplus.pojo;

import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;

@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;
    @Version // 标识乐观锁版本号字段
    private Integer version;
}

User.java

package com.bijian.mybatisplus.pojo;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.bijian.mybatisplus.enums.SexEnum;
import lombok.Data;

@Data
//在实体类类型上添加@TableName("t_user"),标识实体类对应的表,即可成功执行SQL语句
//@TableName("t_user")
public class User {
    /*
    * 1. MyBatis-Plus没有将uid作为主键赋值,在实体类中uid属性上通过@TableId将其标识为主键,即可成功执行SQL语句
    * 2. 若实体类中主键对应的属性为id,而表中表示主键的字段为uid,此时若只在属性id上添加注解@TableId,
    *    则抛出异常Unknown column 'id' in 'field list',即MyBatis-Plus仍然会将id作为表的主键操作,
    *    而表中表示主键的是字段uid此时需要通过@TableId注解的value属性,指定表中的主键字段,
    *    @TableId("uid")或@TableId(value="uid")
    * 3. type属性用来定义主键策略
    *    IdType.ASSIGN_ID(默认):基于雪花算法的策略生成数据id,与数据库id是否设置自增无关
    *    IdType.AUTO: 使用数据库的自增策略,注意,该类型请确保数据库设置了id自增,否则无效
    * 4. 雪花算法是由Twitter公布的分布式主键生成算法,它能够保证不同表的主键的不重复性,以及相同表的主键的有序性。
    * */
    @TableId(value = "id")
    private Long id;

    /*
    * 1. 若实体类中的属性使用的是驼峰命名风格,而表中的字段使用的是下划线命名风格例如实体类属性userName,
    *    表中字段user_name此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格
    * 2. 若实体类中的属性和表中的字段不满足情况1,例如实体类属性name,表中字段username,
    *    此时需要在实体类属性上使用@TableField("username")设置属性所对应的字段名
    * */
    @TableField("name")
    private String name;

    private Integer age;

    private String email;

    private SexEnum sex;

    /*
    * @TableLogic:逻辑删除(使用场景:可以进行数据恢复),真正执行的是修改
    * 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
    * */

}

service

UserService.java

package com.bijian.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.bijian.mybatisplus.pojo.User;

public interface UserService extends IService<User> {

}

UserServiceImpl.java

package com.bijian.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bijian.mybatisplus.mapper.UserMapper;
import com.bijian.mybatisplus.pojo.User;
import com.bijian.mybatisplus.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

resources/mapper

UseMapper.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.bijian.mybatisplus.mapper.UserMapper">

    <!--Map<String, Object> selectMapById(Long id);-->
    <select id="selectMapById" resultType="map">
        select id,name,age,email from t_user where id = #{id}
    </select>

<!--    Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);-->
    <select id="selectPageVo" resultType="User">
        select id,name,age,email from t_user where age > #{age}
    </select>

</mapper>

application.yml

spring:
  profiles:
    active: dev

application-dev.yml

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC
    username: root
    password: 123456

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      # 配置MyBatis-Plus操作表的默认前缀
      table-prefix: t_
      # 配置MyBatis-Plus的主键策略
#      id-type: auto
  # 配置类型别名所对应的包
  type-aliases-package: com.bijian.mybatisplus.pojo
  # 配置扫描通用枚举
  type-enums-package: com.bijian.mybatisplus.enums

test

MybatisPlusTest

  1 package com.bijian.mybatisplus;
  2 
  3 import com.bijian.mybatisplus.mapper.UserMapper;
  4 import com.bijian.mybatisplus.pojo.User;
  5 import org.junit.jupiter.api.Test;
  6 import org.springframework.beans.factory.annotation.Autowired;
  7 import org.springframework.boot.test.context.SpringBootTest;
  8 
  9 import java.lang.reflect.Array;
 10 import java.util.Arrays;
 11 import java.util.HashMap;
 12 import java.util.List;
 13 import java.util.Map;
 14 
 15 @SpringBootTest
 16 public class MybatisPlusTest {
 17     @Autowired
 18     private UserMapper userMapper;
 19 
 20     @Test
 21     public void testSelectList() {
 22         //selectList()根据MP内置的条件构造器查询一个list集合,null表示没有条件,即查询所有
 23         List<User> list = userMapper.selectList(null);
 24         list.forEach(System.out::println);
 25     }
 26 
 27     @Test
 28     public void testInsert() {
 29         //INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
 30         User user = new User();
 31 
 32 //        user.setName("张三");
 33 //        user.setAge(18);
 34 //        user.setEmail("[email protected]");
 35 
 36         user.setName("李四");
 37         user.setAge(20);
 38         user.setEmail("[email protected]");
 39 
 40         int result = userMapper.insert(user);
 41         System.out.println("result:" + result);
 42     }
 43 
 44     @Test
 45     public void testDeleteById(){
 46         //DELETE FROM user WHERE id=?
 47         int result = userMapper.deleteById(1680044786809073666L);
 48         System.out.println(result);
 49     }
 50 
 51     @Test
 52     public void testDeleteByMap(){
 53         //DELETE FROM user WHERE name = ? AND age = ?
 54         Map<String,Object> map = new HashMap<>();
 55         map.put("name","张三");
 56         map.put("age",18);
 57         int result = userMapper.deleteByMap(map);
 58         System.out.println(result);
 59     }
 60 
 61     @Test
 62     public void testDeleteBatchIds(){
 63         //DELETE FROM user WHERE id IN ( ? , ? , ? )
 64         List<Long> list = Arrays.asList(1680047446052380674L, 1680047702899019777L);
 65         int result = userMapper.deleteBatchIds(list);
 66         System.out.println("受影响行数:"+result);
 67     }
 68 
 69     @Test
 70     public void testUpdate(){
 71         // UPDATE user SET name=?, age=?, email=? WHERE id=?
 72         User user = new User();
 73         user.setId(4L);
 74         user.setName("admin");
 75         user.setAge(50);
 76         user.setEmail("[email protected]");
 77         int result = userMapper.updateById(user);
 78         System.out.println("result:" + result);
 79     }
 80 
 81     @Test
 82     public void testSelectById(){
 83         // SELECT id,name,age,email FROM user WHERE id=?
 84         User user = userMapper.selectById("1L");
 85         System.out.println(user);
 86     }
 87 
 88     @Test
 89     public void testSelectBatchIds(){
 90         // SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
 91         List<Long> list = Arrays.asList(1L, 2L, 3L);
 92         List<User> users = userMapper.selectBatchIds(list);
 93         users.forEach(System.out::println);
 94     }
 95 
 96     @Test
 97     public void testSelectByMap(){
 98         // SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
 99         Map<String,Object> map = new HashMap<>();
100         map.put("name","admin");
101         map.put("age",50);
102         List<User> users = userMapper.selectByMap(map);
103         users.forEach(System.out::println);
104     }
105 
106     @Test
107     public void testSelectMapById(){
108         // select id,name,age,email from user where id = ?
109         Map<String, Object> map = userMapper.selectMapById(1L);
110         System.out.println(map); // {name=Jone, id=1, age=18, [email protected]}
111     }
112 }
MybatisPlusTest.java

MyBatisPlusServiceTest

 1 package com.bijian.mybatisplus;
 2 
 3 import com.bijian.mybatisplus.pojo.User;
 4 import com.bijian.mybatisplus.service.UserService;
 5 import org.junit.jupiter.api.Test;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.boot.test.context.SpringBootTest;
 8 
 9 import java.util.ArrayList;
10 
11 @SpringBootTest
12 public class MyBatisPlusServiceTest {
13     @Autowired
14     private UserService userService;
15 
16     @Test
17     public void testGetCount() {
18         // SELECT COUNT( * ) FROM user
19         int count = userService.count();
20         System.out.println("总记录数:" + count);
21     }
22 
23     @Test
24     public void testSaveBatch() {
25         // SQL长度有限制,海量数据插入单条SQL无法实行,
26         // 因此MP将批量插入放在了通用Service中实现,而不是通用Mapper
27         // INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
28         ArrayList<User> users = new ArrayList<>();
29         for (int i = 0; i < 25; i++) {
30             User user = new User();
31             user.setName("sjt" + i);
32             user.setAge(30 + i);
33             user.setEmail("sjt" + i + "@qq.com");
34             users.add(user);
35         }
36         boolean result = userService.saveBatch(users);
37         System.out.println(result);
38     }
39 }
MyBatisPlusServiceTest.java

MyBatisPlusWrapperTest

  1 package com.bijian.mybatisplus;
  2 
  3 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  4 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  6 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  7 import com.bijian.mybatisplus.mapper.UserMapper;
  8 import com.bijian.mybatisplus.pojo.User;
  9 import org.junit.jupiter.api.Test;
 10 import org.junit.platform.commons.util.StringUtils;
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.boot.test.context.SpringBootTest;
 13 
 14 import java.util.List;
 15 import java.util.Map;
 16 
 17 @SpringBootTest
 18 public class MyBatisPlusWrapperTest {
 19 
 20     @Autowired
 21     private UserMapper userMapper;
 22 
 23     @Test
 24     public void test01() {
 25         // 查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息
 26         // SELECT id,name,age,email FROM t_user WHERE (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
 27         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 28         queryWrapper.like("name", "a").between("age", 20, 30).isNotNull("email");
 29         List<User> users = userMapper.selectList(queryWrapper);
 30         users.forEach(System.out::println);
 31     }
 32 
 33     @Test
 34     public void test02() {
 35         // 按年龄降序查询用户,如果年龄相同则按id升序排列
 36         // SELECT id,name,age,email FROM t_user ORDER BY age DESC,id ASC
 37         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 38         queryWrapper.orderByDesc("age").orderByAsc("id");
 39         List<User> users = userMapper.selectList(queryWrapper);
 40         users.forEach(System.out::println);
 41     }
 42 
 43     @Test
 44     public void test03() {
 45         // 删除email为空的用户
 46         // DELETE FROM t_user WHERE (email IS NULL)
 47         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 48         queryWrapper.isNull("email");
 49         int result = userMapper.delete(queryWrapper);
 50         System.out.println("受影响的行数:" + result);
 51     }
 52 
 53     @Test
 54     public void test04() {
 55         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 56         // 将(年龄大于40并且用户名中包含有a)或邮箱为null的用户信息修改
 57         // UPDATE t_user SET age=? WHERE (age > ? AND name LIKE ? OR email IS NULL)
 58 //        queryWrapper.gt("age",40).like("name","a").or().isNull("email");
 59 
 60         // 将用户名中包含有a并且(年龄大于30或邮箱为null)的用户信息修改
 61         // lambda表达式内的逻辑优先运算
 62         // UPDATE t_user SET age=? WHERE (name LIKE ? AND (age > ? OR email IS NULL))
 63         queryWrapper.like("name", "a").and(i -> i.gt("age", 30).or().isNull("email"));
 64         User user = new User();
 65         user.setAge(55);
 66         int result = userMapper.update(user, queryWrapper);
 67         System.out.println("受影响的行数:" + result);
 68     }
 69 
 70     @Test
 71     public void test05() {
 72         // 查询用户信息的username和age字段
 73         // SELECT name,age FROM t_user
 74         // //selectMaps()返回Map集合列表,通常配合select()使用,避免User对象中没有被查询到的列值为null
 75         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 76         queryWrapper.select("name", "age");
 77         List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
 78         maps.forEach(System.out::println);
 79     }
 80 
 81     @Test
 82     public void test06() {
 83         // 查询id小于等于3的用户信息
 84         // SELECT id,name,age,email FROM t_user WHERE (id IN (select id from t_user where id <= 3))
 85         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 86         queryWrapper.inSql("id", "select id from t_user where id <= 3");
 87         List<User> users = userMapper.selectList(queryWrapper);
 88         users.forEach(System.out::println);
 89     }
 90 
 91     @Test
 92     public void test07() {
 93         UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
 94         // 将(年龄大于40或邮箱为null)并且用户名中包含有a的用户信息修改
 95         // UPDATE t_user SET age=? WHERE (name LIKE ? AND (age >= ? OR email IS NULL))
 96         updateWrapper.set("age", 55).like("name", "a").and(i -> i.ge("age", 40).or().isNull("email"));
 97         // 这里必须要创建User对象,否则无法应用自动填充。如果没有自动填充,可以设置为null
 98         int result = userMapper.update(null, updateWrapper);
 99         System.out.println(result);
100     }
101 
102     @Test
103     public void test08() {
104         // 定义查询条件,有可能为null(用户未输入或未选择)
105         // SELECT id,name,age,email FROM t_user WHERE (age >= ? AND age <= ?)
106         String name = null;
107         Integer ageBegin = 10;
108         Integer ageEnd = 24;
109         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
110         if (StringUtils.isNotBlank(name)) {
111             queryWrapper.like("name", "a");
112         }
113         if (ageBegin != null) {
114             queryWrapper.ge("age", ageBegin);
115         }
116         if (ageEnd != null) {
117             queryWrapper.le("age", ageEnd);
118         }
119 
120         List<User> users = userMapper.selectList(queryWrapper);
121         users.forEach(System.out::println);
122     }
123 
124     @Test
125     public void test08_2() {
126         String name = null;
127         Integer ageBegin = 10;
128         Integer ageEnd = 24;
129         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
130         queryWrapper.like(StringUtils.isNotBlank(name), "name", "a")
131                     .ge(ageBegin != null, "age", ageBegin)
132                     .le(ageEnd != null, "age", ageEnd);
133         List<User> users = userMapper.selectList(queryWrapper);
134         users.forEach(System.out::println);
135     }
136 
137     @Test
138     public void test09() {
139         String name = null;
140         Integer ageBegin = 10;
141         Integer ageEnd = 24;
142         LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
143         //避免使用字符串表示字段,防止运行时错误
144         queryWrapper.like(StringUtils.isNotBlank(name),User::getName,name)
145                     .ge(ageBegin != null,User::getAge,ageBegin)
146                     .le(ageEnd!=null,User::getAge,ageEnd);
147         List<User> users = userMapper.selectList(queryWrapper);
148         users.forEach(System.out::println);
149     }
150 
151     @Test
152     public void test10() {
153         LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
154         updateWrapper.set(User::getAge, 55)
155                      .like(User::getName, "a")
156                       .and(i -> i.ge(User::getAge, 40).or().isNull(User::getEmail));
157         int result = userMapper.update(null, updateWrapper);
158         System.out.println(result);
159     }
160 }
MyBatisPlusWrapperTest.java

MybatisPlusEnumTest

 1 package com.bijian.mybatisplus;
 2 
 3 import com.bijian.mybatisplus.enums.SexEnum;
 4 import com.bijian.mybatisplus.mapper.UserMapper;
 5 import com.bijian.mybatisplus.pojo.User;
 6 import org.junit.jupiter.api.Test;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.boot.test.context.SpringBootTest;
 9 
10 @SpringBootTest
11 public class MybatisPlusEnumTest {
12     @Autowired
13     private UserMapper userMapper;
14 
15     @Test
16     public void testSexEnum() {
17         User user = new User();
18         user.setName("Enum");
19         user.setAge(20);
20         //设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库
21         user.setSex(SexEnum.MALE);
22         int result = userMapper.insert(user);
23         System.out.println("result:" + result);
24     }
25 
26 }
MybatisPlusEnumTest.java

MybatisPlusPluginsTest

  1 package com.bijian.mybatisplus;
  2 
  3 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  4 import com.bijian.mybatisplus.mapper.ProductMapper;
  5 import com.bijian.mybatisplus.mapper.UserMapper;
  6 import com.bijian.mybatisplus.pojo.Product;
  7 import com.bijian.mybatisplus.pojo.User;
  8 import org.junit.jupiter.api.Test;
  9 import org.springframework.beans.factory.annotation.Autowired;
 10 import org.springframework.boot.test.context.SpringBootTest;
 11 
 12 import java.util.List;
 13 
 14 @SpringBootTest
 15 public class MybatisPlusPluginsTest {
 16     @Autowired
 17     private UserMapper userMapper;
 18     @Autowired
 19     private ProductMapper productMapper;
 20 
 21     @Test
 22     public void testPage(){
 23         //设置分页参数
 24         Page<User> page = new Page<>(2,5);
 25         userMapper.selectPage(page,null);
 26         //获取分页数据
 27         List<User> list = page.getRecords();
 28         list.forEach(System.out::println);
 29         System.out.println("当前页:"+page.getCurrent());
 30         System.out.println("每页显示的条数:"+page.getSize());
 31         System.out.println("总记录数:"+page.getTotal());
 32         System.out.println("总页数:"+page.getPages());
 33         System.out.println("是否有上一页:"+page.hasPrevious());
 34         System.out.println("是否有下一页:"+page.hasNext());
 35     }
 36 
 37     @Test
 38     public void testSelectPageVo(){
 39         Page<User> page = new Page<>(1,5);
 40         userMapper.selectPageVo(page,30);
 41         List<User> list = page.getRecords();
 42         list.forEach(System.out::println);
 43         System.out.println("当前页:"+page.getCurrent());
 44         System.out.println("每页显示的条数:"+page.getSize());
 45         System.out.println("总记录数:"+page.getTotal());
 46         System.out.println("总页数:"+page.getPages());
 47         System.out.println("是否有上一页:"+page.hasPrevious());
 48         System.out.println("是否有下一页:"+page.hasNext());
 49     }
 50 
 51     @Test
 52     public void testConcurrentUpdate(){
 53         //1、小李
 54         Product p1 = productMapper.selectById(1L);
 55         System.out.println("小李取出的价格:" + p1.getPrice());
 56         //2、小王
 57         Product p2 = productMapper.selectById(1L);
 58         System.out.println("小王取出的价格:" + p2.getPrice());
 59         //3、小李将价格加了50元,存入了数据库 UPDATE t_product SET name=?, price=?, version=1 WHERE id=? AND version=0
 60         p1.setPrice(p1.getPrice()+50);
 61         int result1 = productMapper.updateById(p1);
 62         System.out.println("小李修改结果:" + result1);
 63         //4、小王将商品减了30元,存入了数据库 UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=0
 64         p2.setPrice(p2.getPrice() - 30);
 65         int result2 = productMapper.updateById(p2);
 66         System.out.println("小王修改结果:" + result2);
 67         //最后的结果
 68         Product p3 = productMapper.selectById(1L);
 69         //价格覆盖,最后的结果:70
 70         System.out.println("最后的结果:" + p3.getPrice());
 71     }
 72 
 73     @Test
 74     public void testConcurrentUpdate2(){
 75         //1、小李
 76         Product p1 = productMapper.selectById(1L);
 77         System.out.println("小李取出的价格:" + p1.getPrice());
 78         //2、小王
 79         Product p2 = productMapper.selectById(1L);
 80         System.out.println("小王取出的价格:" + p2.getPrice());
 81         //3、小李将价格加了50元,存入了数据库
 82         p1.setPrice(p1.getPrice()+50);
 83         int result1 = productMapper.updateById(p1);
 84         System.out.println("小李修改结果:" + result1);
 85         //4、小王将商品减了30元,存入了数据库
 86         p2.setPrice(p2.getPrice() - 30);
 87         int result2 = productMapper.updateById(p2);
 88         System.out.println("小王修改结果:" + result2);
 89         //5、失败重试,重新获取version并更新
 90         if (result2==0){
 91             p2 = productMapper.selectById(1L);
 92             p2.setPrice(p2.getPrice()-30);
 93             result2 = productMapper.updateById(p2);
 94         }
 95         System.out.println("小王修改重试的结果:" + result2);
 96         //6、老板看价格
 97         Product p3 = productMapper.selectById(1L);
 98         System.out.println("老板看价格:" + p3.getPrice());
 99     }
100 }
MybatisPlusPluginsTest.java

FastAutoGeneratorTest

 1 package com.bijian.mybatisplus;
 2 
 3 import com.baomidou.mybatisplus.generator.FastAutoGenerator;
 4 import com.baomidou.mybatisplus.generator.config.OutputFile;
 5 import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 6 
 7 import java.util.Collections;
 8 
 9 public class FastAutoGeneratorTest {
10 
11     public static void main(String[] args) {
12         FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus?serverTimezone=UTC", "root", "123456")
13                 .globalConfig(builder -> {
14                     builder.author("bijian") // 设置作者
15                             //.enableSwagger() // 开启 swagger 模式
16                             .fileOverride() // 覆盖已生成文件
17                             .outputDir("D://IdeaProjects//mybatis_plus"); // 指定输出目录
18                 })
19                 .packageConfig(builder -> {
20                     builder.parent("com.bijian") // 设置父包名
21                             .moduleName("mybatisplus") // 设置父包模块名
22                             .pathInfo(Collections.singletonMap(OutputFile.xml, "D://IdeaProjects//mybatis_plus")); // 设置mapperXml生成路径
23                 })
24                 .strategyConfig(builder -> {
25                     builder.addInclude("t_user") // 设置需要生成的表名
26                             .addTablePrefix("t_", "c_"); // 设置过滤表前缀
27                 })
28                 .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
29                 .execute();
30     }
31 
32 }
FastAutoGeneratorTest.java

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bijian</groupId>
    <artifactId>mybatisplus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisplus</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
pom.xml

 

标签:mybatisplus,System,user,println,import,com,MybatisPlus
From: https://www.cnblogs.com/bijian/p/17557403.html

相关文章

  • MyBatisPlus
    一、MyBatisPlus简介SpringBoot整合MyBatisPlus入门程序①:创建新模块mybatis-plus-01③:添加相关的起步依赖多余的文件和依赖配置都可以删除了pom.xml文件如下:<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependen......
  • mybatisPlus 中设置批量更新执行耗时
    设置myBatisPlus中使用批量更新执行的时间耗时短在连接mysql的url后添加&rewriteBatchedStatements=true为什么默认不给这个rewriteBatchedStatements属性设置为true,原来有如下原因:看下executeBatchedInserts究竟干了什么:如果批量语句中的某些语句失败,则默认重......
  • pom.xml增加Mybatisplus的依赖后报错:Factory method 'sqlSessionFactory' threw excep
    出现上面的问题,是版本不匹配导致。<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency&......
  • 1-MyBatisPlus 入门案例与简介
    1.入门案例MybatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提供效率。开发方式基于MyBatis使用MyBatisPlus基于Spring使用MyBatisPlus基于SpringBoot使用MyBatisPlusSpringBoot整合MybatisPlus具体实现步骤为:创建数据库......
  • MyBatisPlus(MP) 使用总结
    mybatisplus(MP)使用总结mybatisplus(MP)是mybatis框架的增强工具,提高开发效率;https://mp.baomidou.com/springboot+mybatis=mapper接口+配置文件1.标准开发@MapperpublicinterfaceUserDaoextendsBaseMapper{}2.分页查询3.条件查询4.条件查询null判断5.查询......
  • MyBatisPlus配置类-配置分页插件,注册为bean对象
    importcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springfra......
  • mybatisplus跨库操作和@Transactional一起使用的问题
    1、当方法使用了@Transactional注解,mybatisplus切换库之前已经有对当前库进行操作的话,切库将不成功;2、当方法使用了@Transactional注解,mybatisplus切换库之前没有对当前库进行操作的话,切库成功,但是@Transactional注解好像没有生效,操作报异常之后上一个操作没有回退;......
  • 分页插件【MybatisPlus】
    //mybatisplus分页插件@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){//1创建MybatisPlusInterceptor拦截器对象MybatisPlusInterceptormpInterceptor=newMybatisPlusInterceptor();//2添加分页拦截器......
  • Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离
    Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离 分类于 实战例子本文ShardingJDBC相关知识主要参考自ShardingJDBC官方文档,更多的用法建议到官网文档查看。前言传统的业务系统都是将数据集中存储至单一数据节点的解决方案,如今随着互联网数据......
  • MybatisPlus自动填充
    importcom.baomidou.mybatisplus.core.handlers.MetaObjectHandler;importlombok.extern.slf4j.Slf4j;importorg.apache.ibatis.reflection.MetaObject;importorg.springframework.stereotype.Component;importjava.time.LocalDateTime;@Slf4j@Componentpublic......