mybatis-plus结合springboot使用

mybatis-plus入门使用-代码仓库:https://gitee.com/DerekAndroid/mybatisPlusDemo.git

mybatis-plus入门使用:

新建数据库,选择排序规则utf8_unicode_ci(不区分大小写),

1.sql准备,user.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

#创建用户表,#初始化数据: usertwo.sql

DROP TABLE IF EXISTS usertwo;
 

CREATE TABLE usertwo (
    id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
    name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
    age INT(11) DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
    manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id',
    create_time DATETIME DEFAULT NULL COMMENT '创建时间',
    CONSTRAINT manager_fk FOREIGN KEY (manager_id)
        REFERENCES usertwo (id)
)  ENGINE=INNODB CHARSET=UTF8;


INSERT INTO usertwo (id, name, age, email, manager_id
	, create_time)
VALUES (1087982257332887553, '大boss', 40, 'boss@baomidou.com', NULL
		, '2019-01-11 14:20:20'),
	(1088248166370832385, '王天风', 25, 'wtf@baomidou.com', 1087982257332887553
		, '2019-02-05 11:12:22'),
	(1088250446457389058, '李艺伟', 28, 'lyw@baomidou.com', 1088248166370832385
		, '2019-02-14 08:31:16'),
	(1094590409767661570, '张雨琪', 31, 'zjq@baomidou.com', 1088248166370832385
		, '2019-01-14 09:15:15'),
	(1094592041087729666, '刘红雨', 32, 'lhm@baomidou.com', 1088248166370832385
		, '2019-01-14 09:48:16');

2.springboot依赖+配置

<?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.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>mybatisPlusDemo</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</artifactId>
		</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>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
			<version>1.18.8</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.3.1.tmp</version>
		</dependency>
		<!--mysql驱动-->
		<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>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.3.1.tmp</version>
		</dependency>
		<!-- mybatisplus逆向工程需要的额外jar包,或者freemaker的包也行 -->
<!--		<dependency>-->
<!--			<groupId>org.apache.velocity</groupId>-->
<!--			<artifactId>velocity-engine-core</artifactId>-->
<!--			<version>2.0</version>-->
<!--		</dependency>-->
		<!-- mybatisplus逆向工程需要的额外jar包,或者freemaker的包也行 -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.30</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<scope>compile</scope>
		</dependency>
	</dependencies>

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

</project>

逆向工程自动生成

根据创建好的数据库执行自动生成mybtais配置文件

注意:freemarker依赖需要配合模板使用

autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());

 自动生成类

package com.example.demo.test;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

public class SqlGenerator {
    @Test
    public void testGenerator(){
        //0.获取当前主项目路径
        String dir = System.getProperty("user.dir");
        String outputDir=dir+"/src/main/java";
        System.out.println("outputDir="+outputDir);
        //1、全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(true)//开启AR模式
                .setAuthor("agen")//设置作者
                //生成路径(一般都是生成在此项目的src/main/java下面)
                .setOutputDir(outputDir)
                .setFileOverride(true)//第二次生成会把第一次生成的覆盖掉
                .setIdType(IdType.AUTO)//主键策略
                .setServiceName("%sService")//生成的service接口名字首字母是否为I,这样设置就没有I
                .setBaseResultMap(true)//生成resultMap
                .setBaseColumnList(true);//在xml中生成基础列
        //2、数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)//数据库类型
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl("jdbc:mysql://localhost:3306/boot_user?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC")
                .setUsername("root")
                .setPassword("123");
        //3、策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setCapitalMode(true)//开启全局大写命名
                .setNaming(NamingStrategy.underline_to_camel)//下划线到驼峰的命名方式
                .setTablePrefix("tb_")//表名前缀
                .setEntityLombokModel(true)//使用lombok
                .setInclude("user");//逆向工程使用的表
        //4、包名策略配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example.demo")//设置包名的parent
                .setMapper("mapper")
                .setService("service")
                .setController("controller")
                .setEntity("entity")
                .setXml("mapper");//设置xml文件的目录
        //5、整合配置
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig);
        //6、执行
        autoGenerator.execute();
    }
}

生成的效果文件

按模板自动生成代码:

注意:baseEntity需要自己创建实现

package com.example.demo.test;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.Test;

public class SqlGenerator {
    @Test
    public void testOne(){
        String dir = System.getProperty("user.dir");
        String outputDir=dir+"/src/main/java";
        System.out.println("outputDir="+outputDir);
        //D:\java\code\mybatisPlusDemo/src/main/java
    }

    @Test
    public void testGenerator(){
        //0.获取当前主项目路径
        String dir = System.getProperty("user.dir");
        String outputDir=dir+"/src/main/java";
        System.out.println("outputDir="+outputDir);

        //1、全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(true)//开启AR模式
                .setAuthor("agen")//设置作者
                //生成路径(一般都是生成在此项目的src/main/java下面)
                .setOutputDir(outputDir)
                .setFileOverride(true)//第二次生成会把第一次生成的覆盖掉
                .setIdType(IdType.AUTO)//主键策略
                .setServiceName("%sService")//生成的service接口名字首字母是否为I,这样设置就没有I
                .setBaseResultMap(true)//生成resultMap
                .setBaseColumnList(true);//在xml中生成基础列
        //2、数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)//数据库类型
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl("jdbc:mysql://localhost:3306/boot_user?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC")
                .setUsername("root")
                .setPassword("123");
        //3、策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setCapitalMode(true)//开启全局大写命名
                .setNaming(NamingStrategy.underline_to_camel)//下划线到驼峰的命名方式
                .setTablePrefix("tb_")//表名前缀
                .setEntityLombokModel(true)//使用lombok
                .setInclude("children");//逆向工程使用的表
        //4、包名策略配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example.demo")//设置包名的parent
                .setMapper("mapper")
                .setService("service")
                .setController("controller")
                .setEntity("entity")
                .setXml("mapper");//设置xml文件的目录
        //5、整合配置
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig);

        // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        //6、执行
        autoGenerator.execute();
    }
}

控制台输入模块us ,输入表名usertwo

 

生成的文件目录

4编写查询语句

package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author agen
 * @since 2020-04-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    public void insertUser(User user) {
        log.info("----------------插入一条记录: insert user----------------");
        userMapper.insert(user);
    }

    public void serviceSave(User user) {
        log.info("----------------service插入一条记录: save user----------------");
        save(user);
    }

    public void selectTest() {
        log.info("----------------按主键查询: where id=2----------------");
        User user = userMapper.selectById(1);
        log.info(user.toString());

        log.info("----------------按主键查询: where id=2 ? and age=?----------------");
        User user1 = new User();
        user1.setId(2L);
        user1.setAge(20);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user1);
        User user2 = userMapper.selectOne(queryWrapper);
        log.info(user2.toString());

    }
}


分页插件

1.配置文件

//Spring boot方式
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {

    @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;
    }
}

2.测试自带分页

package com.example.demo;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {

    @Resource
    private UserMapper mapper;

    @Test
    void contextLoads() {
        System.out.println(("----- selectAll method test ------"));
    }

    @Test
    public void testSlf4j() {
        log.error("----------------------------------baseMapper 自带分页-------------------------------------------------------");
        Page<User> page = new Page<>(1, 3);
        Page<User> userIPage = mapper.selectPage(page, Wrappers.<User>lambdaQuery().ge(User::getAge, 1).orderByDesc(User::getId));
        log.error("总数据 -------------> {}", userIPage.getRecords().toArray());
        log.error("总条数 -------------> {}", userIPage.getTotal() + "当前页数 -------------> {}" + userIPage.getCurrent() +
				"当前每页显示数 -------------> {}" + userIPage.getSize());
    }

}

json 正反序列化

    @Test
    public void testSlf4j() {
        log.error("----------------------------------baseMapper 自带分页-------------------------------------------------------");
        Page<User> page = new Page<>(1, 3);
        page.addOrder(OrderItem.asc("age"));
        Page<User> userIPage = mapper.selectPage(page, Wrappers.<User>lambdaQuery().ge(User::getAge, 20));
        log.error("总数据 -------------> {}", userIPage.getRecords().toString());
        log.error("总条数 -------------> {}", userIPage.getTotal() + "当前页数 -------------> {}" + userIPage.getCurrent() +
                "当前每页显示数 -------------> {}" + userIPage.getSize());

        log.error("----------------------------------json 正反序列化-------------------------------------------------------");
        log.info("page ----------> {}", page.getRecords().toString());
        String json = JSON.toJSONString(page);
        log.info("json ----------> {}", json);
        //{"current":1,"hitCount":false,"orders":[],"pages":6,"records":[{"age":24,"email":"test5@baomidou.com","id":17,"name":"Billie"},{"age":21,"email":"test4@baomidou.com","id":16,"name":"Sandy"},{"age":28,"email":"test3@baomidou.com","id":15,"name":"Tom"}],"searchCount":true,"size":3,"total":17}
}


        //反序列化 json->object
        Page<User> page1 = JSON.parseObject(json, new TypeReference<Page<User>>() {
        });
        log.info("page1.getRecords ----------> {}", page1.getRecords());
        //[User(id=2, name=Jack, age=20, email=test2@baomidou.com), User(id=14, name=Jack, age=20, email=test2@baomidou.com), User(id=13, name=Jack, age=20, email=test2@baomidou.com)]
    }

 

表名、表字段改变,同步绑定操作

通过配置TableName同步更新表明

@TableName("user")
public class User extends Model<User> {

    private static final long serialVersionUID=1L;

    /**
     * 主键ID
     */
      @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 姓名
     */
    @TableField("name")
    private String name;

配置多个mapper路径

springboot项目有时会涉及多数据源,因为我们通常每个数据源创建不同的包路径,mapper.xml的路径也不一样,这个时候就需要引入多个路径。

数据源1,mapper接口路径在 mapper包下面,mapper.xml 路径在 resources/mappers/下面; 

数据源2,mapper接口路径在 mapper/other包下面,mapper.xml 路径在 resources/mappers/other下面:

配置总共分两步:

第一步 :

在mybatisplus配置类里面修改扫描包路径:

@SpringBootApplication
@MapperScan({"com.example.demo.mapper","com.example.demo.**.mapper"})
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

第二步:

修项目的application.yml配置文件中配置mapper.xml路径如下:

mybatis-plus:
#   1.配置多个classpath:用,分割开  2.Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件)
  mapper-locations: classpath*:/mapper/us/*Mapper.xml,classpath*:/mapper/*Mapper.xml

使用 Wrapper 自定义SQL

注意,如果使用xml方式,需要配置正确的路径

此处采用注解+xml的形式

public interface UserMapper extends BaseMapper<User> {


    @Select("SELECT * FROM user where name = #{name}")
    List<User> selectByName(@Param("name") String name);

    List<User> selectByNameTwo(@Param("name") String name);

    @Select("select * from user ${ew.customSqlSegment}")
    List<User> mySelectMap(@Param(Constants.WRAPPER) Wrapper wrapper);
}

xml配置

    <select id="selectByNameTwo" resultType="com.example.demo.entity.User">
        SELECT * FROM user where name = #{name}
    </select>

测试

   @Test
    public void testMap() {
        log.info("------------------------------使用 Wrapper 自定义SQL---------->-");
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.like("name", "m").eq("age", 28);
        List<User> name = mapper.mySelectMap(wrapper);
        log.info("name----------> {}" + name.toString());

        List<User> users = mapper.selectByName("Tom");
        log.info("name----------> {}" + users.toString());

        log.info("------------------------------使用 Wrapper.xml文件 自定义SQL---------->-");
        List<User> tom = mapper.selectByNameTwo("Tom");
        log.info("tom----------> {}" + tom.toString());
    }

条件查询

   @Test
    public void testUserTwo() {
        log.info("------------------------------查询全部--------->-");
        List<Usertwo> usertwos = usertwoMapper.selectList(null);
        log.info("usertwos----------> {}" + usertwos.toString());

        log.info("------------------------------SELECT * FROM usertwo WHERE name like '%雨%' and age<40--------->-");
        QueryWrapper<Usertwo> wrapper = new QueryWrapper();
        wrapper.like("name", "雨").lt("age", 40);
        List<Usertwo> usertwos0 = usertwoMapper.selectList(wrapper);
        log.info("usertwos0----------> {}" + usertwos0.toString());

//        名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
        log.info("------------------------------SELECT * FROM usertwo WHERE name like '%雨%' and age between 20 and 40 and email is not null--------->-");
        QueryWrapper<Usertwo> wrapper1 = new QueryWrapper();
        wrapper.like("name", "雨").between("age", 20, 40).isNotNull("email");
        List<Usertwo> usertwos1 = usertwoMapper.selectList(wrapper);
        log.info("usertwos1-----123-----> {}" + usertwos1.toString());

//名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
        log.info("------------------------------name like '王%' or age>=25 order by age desc,id asc--------->-");
        QueryWrapper<Usertwo> wrappe2 = new QueryWrapper();
        wrappe2.likeRight("name", "王").or().ge("age", "25").orderByDesc("age").orderByAsc("id");
        List<Usertwo> usertwos2 = usertwoMapper.selectList(wrappe2);
        log.info("usertwos2----------> {}" + usertwos2.toString());

        //创建日期为2019年2月14日并且直属上级为名字为王姓
        log.info("------------------------------date_format(create_time,'%Y-%m-%d')='2019-02-14' and manager_id in (select id from user where name like '王%')--------->-");
        QueryWrapper<Usertwo> wrappe3 = new QueryWrapper();
        wrappe3.apply("date_format(create_time,'%Y-%m-%d') = {0}", "2019-02-14").inSql("manager_id", "select id from usertwo where name like '王%'");
        List<Usertwo> usertwos3 = usertwoMapper.selectList(wrappe3);
        log.info("usertwos3----------> {}" + usertwos3.toString());

//        5、名字为王姓并且(年龄小于40或邮箱不为空)
        log.info("------------------------------name like '王%' and (age<40 or email is not null)--------->-");
        QueryWrapper<Usertwo> wrapper4 = new QueryWrapper<>();
        wrapper4.likeRight("name", "王").and(i -> i.lt("age", 40).or().isNotNull("email"));
        List<Usertwo> usertwos4 = usertwoMapper.selectList(wrapper4);
        log.info("usertwos4----------> {}" + usertwos4.toString());
//        6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
        log.info("------------------------------name like '王%' or (age<40 and age>20 and email is not null)--------->-");
        QueryWrapper<Usertwo> wrapper5 = new QueryWrapper<>();
        wrapper5.likeRight("name", "%王%").or(wq -> wq.lt("age", 40).gt("age", 20).isNotNull("email"));
        List<Usertwo> usertwos5 = usertwoMapper.selectList(wrapper5);
        log.info("usertwos5----------> {}" + usertwos5.toString());

//        7、(年龄小于40或邮箱不为空)并且名字为王姓
        log.info("------------------------------(age<40 or email is not null) and name like '王%'--------->-");
        QueryWrapper<Usertwo> wrapper6 = new QueryWrapper<>();
        wrapper6.nested(wq -> wq.lt("age", 40).isNotNull("email")).likeRight("name", "%王%");
        wrapper6.likeRight("name", "%王%").and(wq -> wq.lt("age", 40).isNotNull("email"));
        List<Usertwo> usertwos6 = usertwoMapper.selectList(wrapper6);
        log.info("usertwos6----------> {}" + usertwos6.toString());
//        8、年龄为30、31、34、35
        log.info("------------------------------age in(30,31,34,35)--------->-");
        QueryWrapper<Usertwo> wrapper7 = new QueryWrapper<>();
        wrapper7.in("age", 30, 31, 32, 34, 35);
        List<Usertwo> usertwos7 = usertwoMapper.selectList(wrapper7);
        log.info("usertwos7----------> {}" + usertwos7.toString());
        //拉姆达表达式的语法糖 list.forEach((String t) -> System.out.println(t));
        usertwos7.forEach(System.out::println);
//        9、只返回满足条件的其中一条语句即可
        log.info("------------------------------age in(30,31,34,35)--------->-");
        QueryWrapper<Usertwo> wrapper8 = new QueryWrapper<>();
        wrapper8.in("age", 30, 31, 32, 34, 35).last("limit 1");
        List<Usertwo> usertwos8 = usertwoMapper.selectList(wrapper8);
        log.info("usertwos8----------> {}" + usertwos8.toString());
    }

 select中字段不全部出现的查询

    @Test
    public void testSelect() {
        log.info("select中字段不全部出现的查询");
//        10、名字中包含雨并且年龄小于40(需求1加强版)
        log.info("---------------------select id,name from usertwo where name like '%雨%' and age<40------------------>-");
        QueryWrapper<Usertwo> wrapper1 = new QueryWrapper<>();
        wrapper1.select("id", "name").like("name", "雨").lt("age", 40);
        List<Usertwo> usertwos1 = usertwoMapper.selectList(wrapper1);
        log.info("usertwos1----------> {}" + usertwos1.toString());
        log.info("----------------------select id,name,age,email from usertwo where name like '%雨%' and age<40----------------------->");
        QueryWrapper<Usertwo> wrapper2 = new QueryWrapper<>();
        wrapper2.select(Usertwo.class, qw -> !qw.getColumn().equals("manager_id") && !qw.getColumn().equals("create_time")).like("name", "雨").lt("age", 40);
        List<Usertwo> usertwos2 = usertwoMapper.selectList(wrapper2);
        log.info("usertwos2----------> {}" + usertwos2.toString());
    }

condition判断条件

    @Test
    public void testCondition() {
        log.info("------------------------------condition判断条件--------->-");
        QueryWrapper<Usertwo> wrapper1 = new QueryWrapper<>();
        String name = "雨";
        String email = "";
        //第一个入参boolean condition表示该条件是否加入最后生成的sql中.email为空,所以不查询
        //SELECT name,age FROM usertwo WHERE (name LIKE ?)
        wrapper1.like(!StringUtils.isEmpty(name), "name", name).like(!StringUtils.isEmpty(email), "email", email).select("name", "age");
        List<Usertwo> usertwos1 = usertwoMapper.selectList(wrapper1);
        log.info("usertwos1----------> {}" + usertwos1.toString());
    }

 insert数据的时候,如何排除非表中字段

    @Test
    public void testExit() {
        log.info("------------------------------insert数据的时候,如何排除非表中字段?--------->-");
        User user = new User();
        user.setName("agen");
        user.setAge(18);
        user.setMessgeFlag("我是用来标记的信息,不会存放在数据库中");
        int insert = mapper.insert(user);
        log.info("insert----------> {}" + insert);
    }

主键策略-id

sql

DROP TABLE IF EXISTS userthree;
 
CREATE TABLE userthree
(
	id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);
 
DELETE FROM userthree;
 
INSERT INTO userthree (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

测试代码

    @Test
    public void testInsertUserThree() {
        log.info("------------------------------ UserThree insert数据--------->-");
        Userthree usertwo = new Userthree();
        usertwo.setName("agen");
        usertwo.setAge(18);
        usertwo.setEmail("wtf2@baomidou.com");
        int insert = userthreeMapper.insert(usertwo);
        log.info("insert----------> {}" + insert);
    }

#auto自动增加,5->6
   

 @TableId(value = "id", type = IdType.AUTO)
private Long id;

  Preparing: INSERT INTO userthree ( name, age, email ) VALUES ( ?, ?, ? )

#默认使用(IdWorker)推特雪花算法生成id

修改主键类型

ALTER TABLE userthree CHANGE COLUMN id id BIGINT(20);

代码

    @TableId(value = "id", type = IdType.NONE)
    @TableId(value = "id", type = IdType.ID_WORKER)
    private Long id;

Preparing: INSERT INTO userthree ( id, name, age, email ) VALUES ( ?, ?, ?, ? ) 
Parameters: 1254971356540428289(Long), agen(String), 18(Integer), wtf2@baomidou.com(String)

#字符类型uuid

修改主键类型

ALTER TABLE userthree CHANGE COLUMN id id VARCHAR(32) NOT NULL;

代码

 @TableId(value = "id", type = IdType.UUID)
    private String id;


Preparing:INSERT INTO userthree ( id, name, age, email ) VALUES ( ?, ?, ?, ? ) 
Parameters: c49fc6bb50330e33de7f57ec718e7ee8(String), agen(String), 18(Integer), wtf2@baomidou.com(String)

#字符类型-IdWorker雪花算法

@TableId(value = "id", type = IdType.ID_WORKER_STR)


Preparing: INSERT INTO userthree ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
Parameters: 1254979400980598786(String), agen(String), 18(Integer), wtf2@baomidou.com(String)    

整体效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值