MyBatis Plus——简单入门

一、快速创建

(1)配置pom.xml

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>

        <!-- 整合MyBatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
    </dependencies>

(2)application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springBoot?serverTimezone=UTC
    username: root
    password: 147250
    driver-class-name: com.mysql.cj.jdbc.Driver
# 打印sql语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

(3)Student

@Data
public class Student {
    private Long id;
    private String name;
    private Integer age;
    private LocalDate birthday;
}

(4)StudentRepository

@Repository
public interface StudentRepository extends BaseMapper<Student> {

}

(5)application

@SpringBootApplication
@MapperScan("com.lin.repository")
public class MybatisplusApplication {

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

}

(6)测试

@SpringBootTest
class StudentRepositoryTest {
    @Autowired
    private StudentRepository studentRepository;
    @Test
    void test(){
        studentRepository.selectList(null).forEach(System.out::println);
    }
}

二、常用注解

  • @TableName :指定数据库的表名。如果实体类与表名相同则不需要指定
  • @TableId :指定主键
    1. value :主键字段名
    2. type :主键生成策略 IdType.
描述
AUTO自增
NONEMP自动生成随机数,雪花算法
INPUT开发者手动赋值
ASSIGN_IDMP分配id,类型为Long,Integer,String
ASSIGN_UUID分配uuid,类型为String
  • @TableField :指定其他字段

    1. value:字段名
    2. exist :是否为数据库字段
    3. select :是否查询次字段
    4. fill :自动填充时机 FieldFill. (应用:创建时间和更新时间)
  • @Verson :标记乐观锁

  • @EnumValue :映射枚举

    public enum SexEnum {
        BOY(0,"男孩"),
        GIRL(1,"女孩");
    
        @EnumValue
        private Integer code;
        private String msg;
    
        SexEnum(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    }
    
    
    mybatis-plus:
      type-enums-package: com.lin.enums
    
  • @TableLogic
    映射逻辑删除

    @TableLogic
        private Integer deleted;
    
    global-config:
        db-config:
          logic-not-delete-value: 0
          logic-delete-field: 1
    

三、creat_time和update_time

(1)添加注解

@TableField(fill = FieldFill.INSERT)
   private Date createTime;
   @TableField(fill = FieldFill.INSERT_UPDATE)
   private Date updateTime;

(2)添加handler类设置规则

@Component
public class MyMetaObjectHandler 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);
    }
}

若时间与当前系统时间不相同,设置时区即可解决jdbc:mysql://localhost:3306/springBoot?serverTimezone=Asia/Shanghai

四、CRUD

查询

(1)selectList

  • 查询所有
studentRepository.selectList(null).forEach(System.out::println);
  • 单条件查询
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
studentQueryWrapper.eq("name", "张三");
studentRepository.selectList(studentQueryWrapper).forEach(System.out::println);
  • 多条件查询
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
HashMap<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 20);
studentQueryWrapper.allEq(map);
studentRepository.selectList(studentQueryWrapper).forEach(System.out::println);

  • 条件

    • 小于
    studentQueryWrapper.lt("age", 20);
    
    • 小于等于
    studentQueryWrapper.le("age", 20);
    
    • 大于
    studentQueryWrapper.gt("age", 20);
    
    • 大于等于
    studentQueryWrapper.ge("age", 20);
    
    • 不等于
    studentQueryWrapper.ne("age", 20);
    
    • like
    studentQueryWrapper.like("name", "张");
    // like '%三'
    studentQueryWrapper.likeLeft("name", "三");
    // like ‘张%’
    studentQueryWrapper.likeRight("name", "张");
    
    • 升序
    studentQueryWrapper.orderByAsc("age");
    
    • 降序
    studentQueryWrapper.orderByDesc("age");
    

(2)selectById;

  • 通过id查找
studentRepository.selectById(5);

(3)selectBatchIds

  • id in (5,6,7)
studentRepository.selectBatchIds(Arrays.asList(5,6,7));

(4)selectByMap

  • 多条件查询(只能做等值判断,逻辑判断还需要Wrapper来完成)
HashMap<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 20);
studentRepository.selectByMap(map);

(5)selectMaps

  • 将结果封装成map集合
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
studentQueryWrapper.eq("name", "张三");
System.out.println(studentRepository.selectMaps(studentQueryWrapper));

(6)selectCount

  • 符合条件的数目
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
studentQueryWrapper.eq("name", "张三");
studentRepository.selectCount(studentQueryWrapper);

(7)selectPage

分页查询

7.1 新建MyBatisPlusConfig添加配置

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

7.2 设置

// 第一页,每页2条记录
Page<Student> studentPage = new Page<>(1,2);
Page<Student> selectPage = studentRepository.selectPage(studentPage, null);
// 每页记录数
System.out.println(selectPage.getSize());
// 总记录数
System.out.println(selectPage.getTotal());
// 遍历记录
selectPage.getRecords().forEach(System.out::println);

(8)selectObjs

  • 获取所有id
studentRepository.selectObjs(null).forEach(System.out::println);

(9)selectOne

查询一条记录

(10)selectMapsPage

将分页记录封装成map集合

自定义sql(多表关联查询)

(1)VO实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ClassesVO {
    private Long id;
    private String name;
    private Integer age;
    private LocalDate birthday;
    private Long c_name;
}

(2)Repository

@Repository
public interface StudentRepository extends BaseMapper<Student> {
    @Select("select id,name,age,birthday,c_name from student,classes  where cid=c_id and id=#{id}")
    List<ClassesVO> findClassById(Integer id);
}

(3)调用

studentRepository.findClassById(3).forEach(System.out::println);

添加

Student student = new Student();
student.setName("张三");
student.setAge(20);
student.setBirthday(LocalDate.parse("1978-06-18"));
studentRepository.insert(student);

修改

// 按id更新
Student student = studentRepository.selectById(2);
student.setAge(500);
studentRepository.updateById(student);
// 按其他条件更新
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三");
studentRepository.update(student,wrapper);

删除

// 删除单个id
studentRepository.deleteById(5);
// 删除多个id
studentRepository.deleteBatchIds(Arrays.asList(5,6));
// 按条件删除
studentRepository.delete(wrapper);
studentRepository.deleteByMap(map);

五、MyBatisPlus自动生成

(1)配置pom文件

	<!-- MyBatisPlus自动生成 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6.2</version>
        </dependency>

(2)Main

package com.lin;

import com.baomidou.mybatisplus.annotation.DbType;
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;

public class Main {
    public static void main(String[] args) {
        // 创建generator对象
        AutoGenerator autoGenerator = new AutoGenerator();
        // 数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/springboot?serverTimezone=Asia/Shanghai");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("147250");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        autoGenerator.setDataSource(dataSourceConfig);
        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setServiceName("%sService");
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("lin");
        autoGenerator.setGlobalConfig(globalConfig);
        // 包信息
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.lin.mybatisplus");
        packageConfig.setModuleName("generator");
        packageConfig.setController("controller");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setEntity("entity");
        autoGenerator.setPackageInfo(packageConfig);
        // 配置策略
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        autoGenerator.setStrategy(strategyConfig);

        autoGenerator.execute();

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值