window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

Mybatis-plus 下

Mybatis-plus 下

查询操作

1.查询单个用户

@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}
15

2.查询多个用户

@Test
public void testSelectById(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}
16

3.条件查询

@Test
public void testSelectById(){
    HashMap<String,Object> map = new HashMap<>();
    //自定义查询条件
    map.put("name","小张");
    map.put("age",18);
    List<User> users1 = userMapper.selectByMap(map);
    users1.forEach(System.out::println);
}
17

分页查询

1.配置拦截器

@EnableTransactionManagement
@Configuration
@MapperScan("com.zc.mapper")
public class MyBatisPlusConfig {
    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

2.书写方法

@Test
public void Page(){
    //参数1: 第几页 ;  参数2    页面大小,几条数据
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);

    page.getRecords().forEach(System.out::println);
    //一共有多少条数据
    System.out.println(page.getTotal());

}

此时是 第1页,每页有5条数据

18

删除操作

1.删除单个用户

@Test
public void DeleteById(){
    userMapper.deleteById(1374350451559940099L);
}

19

2.删除多个用户

@Test
public void DeleteById(){
    userMapper.deleteBatchIds(Arrays.asList(4,5));
}

20

3.按条件删除用户

@Test
public void DeleteById(){
    HashMap<String,Object> map = new HashMap<>();
    map.put("name","小李");
    userMapper.deleteByMap(map);
}

21

逻辑删除

物理删除:从数据库中直接移除
逻辑删除:再数据库中没有被移除,而是通过一个变量来让他失效!deleted =0=> deleted =1

步骤:

1.数据表中增加一个 deleted 字段

注意,不要添加成delete字段,delete为关键字,会出错

22

2.实体类加入字段、注解

@TableLogic   //逻辑删除
private Integer deleted;

3.配置文件

## 全局逻辑删除的实体字段名(如果配置这个,可以不添加实体类中的逻辑删除注解)
mybatis-plus.global-config.db-config.logic-delete-field=deleted
# 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0

4.测试

删除操作:

@Test
public void TableLogic(){
    userMapper.deleteById(1374350451559940101L);
}

虽然执行的是删除操作,但是实际上逻辑删除会更新deleted字段,而不是直接删除

23

24

查询操作:

既然没有删除该语句,那可以查询到吗?

@Test
public void TableLogic(){
    userMapper.selectById(1374350451559940101L);
}

25

上图可以看出,他会查询deleted字段为0为前提的数据,如果被逻辑删除过的数据,deleted字段为1,查询不到。

条件构造器

当前我的数据库数据为:

12

测试一

name不为空,邮箱不为空,年龄大于等于12 的用户

@Test
void test1() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.isNotNull("name")
        .isNotNull("email")
        .ge("age",12);
    userMapper.selectList(wrapper);
}

12

测试二

查询名字:小张

查询一个数据时,使用selectOne,查询多个数据,可以使用List或者Map

@Test
void test2() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","小张");
    User user = userMapper.selectOne(wrapper);
    System.out.println(user);
}

13

测试三

查询年龄10-15之间的

selectCount直接返回Integer类型,统计查到了的数据条数

@Test
void test3() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.between("age",10,15);
    Integer integer = userMapper.selectCount(wrapper);
    System.out.println(integer);
}

15

测试四

模糊查询

  • notLike():不包含
  • likeRight():效果与 x% 相同
  • likeLeft():效果与 %x 相同
@Test
void test4() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.notLike("name","邦")  
        .likeRight("email","t");
    List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
    maps.forEach(System.out::println);
}

16

测试五

复杂查询

@Test
void test5() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.inSql("id","select id from user where id<3");
    List<Object> objects = userMapper.selectObjs(wrapper);
    objects.forEach(System.out::println);
}

17

测试六

  • orderBy() :正序排序

  • orderByDesc() :倒序排序

@Test
void test6() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.orderByDesc("id");
    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

18

代码自动生成器

1.导入依赖

<!-- lombok  -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus  -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>
<!-- 代码生成器     -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.0-RC2</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>
<!-- Swagger2    -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

2.配置自动生成代码

在Test文件夹中,创建一个新类:cccc

public class ZcCode {
    public static void main(String[] args) {
        //代码生成器
        AutoGenerator mpg = new AutoGenerator();
        
        //.....其余代码
        
         //执行
        mpg.execute();   
    }
}

全局配置

GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("MoYu");               //作者名
gc.setOpen(false);                  //是否打开资源管理器
gc.setFileOverride(false);          //是否覆盖
gc.setServiceName("%sService");     //去Service的I前缀
gc.setIdType(IdType.ID_WORKER);     //ID类型,设置的为 全局唯一ID 
gc.setDateType(DateType.ONLY_DATE); //Date类型
gc.setSwagger2(true);               //开启Swagget2
mpg.setGlobalConfig(gc);

包的配置

PackageConfig pc = new PackageConfig();
// pc.setModuleName("");          //Controller路径  xxx/实体类名
pc.setParent("com.zc");           //父类文件夹路径
pc.setEntity("entity");           //实体类文件夹
pc.setMapper("mapper");           //mapper文件夹
pc.setService("service");         //service文件夹
pc.setController("controller");   //controller文件夹
mpg.setPackageInfo(pc);

设置数据源

DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("148729");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);

策略配置

StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); // 设置要映射的表名,可以多个表一直写  “xxxx”,"xxxx"
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自动lombok;
// 逻辑删除配置
strategy.setLogicDeleteFieldName("deleted");
// 自动填充配置
TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 乐观锁
strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);

运行

这是生成的架构文件夹:

19

生成之后的代码以及架构都是很规范的,大家可以自己测试一下

个人博客为:
MoYu's HomePage
MoYu's Gitee Blog

posted @ 2021-04-15 22:54  MoYu-zc  阅读(152)  评论(0编辑  收藏  举报