我是靠谱客的博主 调皮墨镜,最近开发中收集的这篇文章主要介绍MyBatis Plus——简单入门一、快速创建二、常用注解三、creat_time和update_time四、CRUD查询添加修改删除五、MyBatisPlus自动生成,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
目录
- 一、快速创建
- (1)配置pom.xml
- (2)application.yml
- (3)Student
- (4)StudentRepository
- (5)application
- (6)测试
- 二、常用注解
- 三、creat_time和update_time
- (1)添加注解
- (2)添加handler类设置规则
- 四、CRUD
- 查询
- (1)selectList
- (2)selectById;
- (3)selectBatchIds
- (4)selectByMap
- (5)selectMaps
- (6)selectCount
- (7)selectPage
- 7.1 新建MyBatisPlusConfig添加配置
- 7.2 设置
- (8)selectObjs
- (9)selectOne
- (10)selectMapsPage
- 自定义sql(多表关联查询)
- (1)VO实体类
- (2)Repository
- (3)调用
- 添加
- 修改
- 删除
- 五、MyBatisPlus自动生成
- (1)配置pom文件
- (2)Main
一、快速创建
(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 :指定主键
- value :主键字段名
- type :主键生成策略 IdType.
值 | 描述 |
---|---|
AUTO | 自增 |
NONE | MP自动生成随机数,雪花算法 |
INPUT | 开发者手动赋值 |
ASSIGN_ID | MP分配id,类型为Long,Integer,String |
ASSIGN_UUID | 分配uuid,类型为String |
-
@TableField :指定其他字段
- value:字段名
- exist :是否为数据库字段
- select :是否查询次字段
- 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();
}
}
最后
以上就是调皮墨镜为你收集整理的MyBatis Plus——简单入门一、快速创建二、常用注解三、creat_time和update_time四、CRUD查询添加修改删除五、MyBatisPlus自动生成的全部内容,希望文章能够帮你解决MyBatis Plus——简单入门一、快速创建二、常用注解三、creat_time和update_time四、CRUD查询添加修改删除五、MyBatisPlus自动生成所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复