springboot:整合mybatis-plus

红太狼 2024-04-01 14:27 16阅读 0赞

文章目录

  • springboot:整合mybatis-plus
    • 一、项目搭建
      • 创建数据库
      • 导入依赖
      • 填写配置
      • 相关类的创建
    • 二、测试CURD
      • 新增
      • 更新
        • 根据id进行更新
        • 根据条件更新update
      • 查询
      • 分页查询
        • 不带条件的分页查询
        • 带条件的分页查询
      • 删除
    • 三、逻辑删除配置
    • 四、自动填充配置
      • 自定义填充类
      • 配置自定义填充
      • 在实体类上添加注释
      • 注意
    • 五、主键配置
        • 字段上使用注释
      • 配置全局主键自增
    • 六、注解
      • @TableName
      • @TableId
      • @TableField

springboot:整合mybatis-plus

一、项目搭建

创建数据库

  1. CREATE TABLE `company` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  3. `name` varchar(255) DEFAULT NULL COMMENT '名称',
  4. `contact` varchar(50) DEFAULT NULL COMMENT '联系人',
  5. `contactType` varchar(50) DEFAULT NULL COMMENT '联系方式',
  6. `createTime` bigint(20) DEFAULT NULL COMMENT '创建时间',
  7. `updateTime` bigint(20) DEFAULT NULL COMMENT '修改时间',
  8. `removed` int(2) DEFAULT NULL COMMENT '是否删除(0:存在,-1:删除)',
  9. `deleteTime` bigint(20) DEFAULT NULL COMMENT '删除时间',
  10. PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='公司单位';

导入依赖

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-boot-starter</artifactId>
  4. <version>3.4.1</version>
  5. </dependency>

注意:这里不要同事导入mybatis和mybatis-plus的依赖,会出现依赖冲突,本人在上面踩雷,排插错误很久

填写配置

  1. package com.mye.cloudboxdcim.configuration;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.baomidou.mybatisplus.annotation.IdType;
  4. import com.baomidou.mybatisplus.core.MybatisConfiguration;
  5. import com.baomidou.mybatisplus.core.config.GlobalConfig;
  6. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  7. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  8. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  9. import com.mye.cloudboxdcim.common.GlobalConstant;
  10. import com.mye.cloudboxdcim.framework.engine.mybatisplus.MyMetaObjectHandler;
  11. import org.apache.ibatis.session.SqlSessionFactory;
  12. import org.apache.ibatis.type.JdbcType;
  13. import org.mybatis.spring.SqlSessionTemplate;
  14. import org.mybatis.spring.annotation.MapperScan;
  15. import org.springframework.beans.factory.annotation.Qualifier;
  16. import org.springframework.context.annotation.Bean;
  17. import org.springframework.context.annotation.Configuration;
  18. import org.springframework.context.annotation.Primary;
  19. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  20. import org.springframework.transaction.annotation.EnableTransactionManagement;
  21. import org.springframework.util.StringUtils;
  22. import javax.sql.DataSource;
  23. /**
  24. * @ClassName MysqlConfiguration
  25. * @Description mysql配置类
  26. * @Author hl
  27. * @Date 2022/10/31 15:50
  28. * @Version 1.0
  29. */
  30. @Configuration
  31. @EnableTransactionManagement
  32. @MapperScan(basePackages = {
  33. "com.mye.cloudboxdcim.framework.api.mapper"}, sqlSessionFactoryRef = "mybatisSqlSession")
  34. public class MysqlConfiguration {
  35. @Bean(name = "dataSource")
  36. @Primary
  37. public DataSource dataSource() throws Exception {
  38. String mysqlHost = System.getenv(GlobalConstant.MYSQL_HOST);
  39. mysqlHost = "61.184.241.171";
  40. if (StringUtils.isEmpty(mysqlHost)) {
  41. throw new Exception("env MYSQL_HOST do not set!");
  42. }
  43. String mysqlPort = System.getenv(GlobalConstant.MYSQL_PORT);
  44. if (StringUtils.isEmpty(mysqlPort)) {
  45. mysqlPort = "3306";
  46. }
  47. String mysqlUsername = System.getenv(GlobalConstant.MYSQL_USERNAME);
  48. if (StringUtils.isEmpty(mysqlUsername)) {
  49. mysqlUsername = "username";
  50. }
  51. String mysqlPassword = System.getenv(GlobalConstant.MYSQL_PASSWORD);
  52. if (StringUtils.isEmpty(mysqlPassword)) {
  53. mysqlPassword = "password";
  54. }
  55. String mysqlDB = System.getenv(GlobalConstant.MYSQL_DB);
  56. if (StringUtils.isEmpty(mysqlDB)) {
  57. mysqlDB = "dbname";
  58. }
  59. mysqlHost = "172.100.20.23";
  60. mysqlPort = "3306";
  61. mysqlUsername = "root";
  62. mysqlPassword = "root";
  63. mysqlDB = "cloud_box_dcim";
  64. DruidDataSource dataSource = new DruidDataSource();
  65. dataSource.setUrl("jdbc:mysql://" + mysqlHost + ":" + mysqlPort + "/" + mysqlDB
  66. + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true");
  67. dataSource.setPassword(mysqlPassword);
  68. dataSource.setUsername(mysqlUsername);
  69. dataSource.setMaxActive(100);
  70. dataSource.setMaxWait(60000);
  71. dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  72. dataSource.setMinEvictableIdleTimeMillis(300000);
  73. dataSource.setTimeBetweenEvictionRunsMillis(60000);
  74. dataSource.setInitialSize(5);
  75. dataSource.setMinIdle(1);
  76. return dataSource;
  77. }
  78. @Bean(name = "transactionManager")
  79. @Primary
  80. public DataSourceTransactionManager transactionManager() throws Exception {
  81. return new DataSourceTransactionManager(dataSource());
  82. }
  83. @Bean("mybatisSqlSession")
  84. public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource")DataSource dataSource,@Qualifier("mybatisPlusInterceptor")MybatisPlusInterceptor mybatisPlusInterceptor) throws Exception {
  85. MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
  86. /* 数据源 */
  87. sqlSessionFactory.setDataSource(dataSource);
  88. MybatisConfiguration configuration = new MybatisConfiguration();
  89. configuration.setJdbcTypeForNull(JdbcType.NULL);
  90. /* 驼峰转下划线 */
  91. configuration.setMapUnderscoreToCamelCase(false);
  92. //日志打印
  93. // configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
  94. /* 分页插件 */
  95. configuration.addInterceptor(mybatisPlusInterceptor);
  96. sqlSessionFactory.setConfiguration(configuration);
  97. /* 全局设置 */
  98. GlobalConfig globalConfig = new GlobalConfig();
  99. globalConfig.setBanner(false);
  100. //配置自动填充功能
  101. globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
  102. GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
  103. /* id自增 */
  104. dbConfig.setIdType(IdType.AUTO);
  105. //全局逻辑删除的实体字段名(since 3.3.0,配置后可以不加步骤2的注解)
  106. dbConfig.setLogicDeleteField("removed");
  107. //逻辑已删除值(默认为 -1)
  108. dbConfig.setLogicDeleteValue("-1");
  109. //逻辑未删除值(默认为 0)
  110. dbConfig.setLogicNotDeleteValue("0");
  111. globalConfig.setDbConfig(dbConfig);
  112. sqlSessionFactory.setGlobalConfig(globalConfig);
  113. return sqlSessionFactory.getObject();
  114. }
  115. /**
  116. * 3.4.0之后提供的拦截器的配置方式
  117. */
  118. @Bean
  119. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  120. MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  121. mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  122. return mybatisPlusInterceptor;
  123. }
  124. @Bean
  125. public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
  126. return new SqlSessionTemplate(sqlSessionFactory);
  127. }
  128. }

相关类的创建

实体类

  1. @TableName("company")
  2. public class Company {
  3. private Integer id;
  4. private String name;
  5. private String contact;
  6. private String contactType;
  7. private Long createTime;
  8. private Long updateTime;
  9. private Long deleteTime;
  10. private int removed;
  11. //省略get、set方法
  12. }

mapper:这里要使用mybatis-plus,需要在mapper继承BaseMapper

  1. @Repository
  2. @Mapper
  3. public interface CompanyMapper extends BaseMapper<Company> {
  4. }

二、测试CURD

新增

  1. int insert(T entity);
  2. @SpringBootTest(classes = CloudBoxDcimApplication.class)
  3. @RunWith(SpringRunner.class)
  4. public class MybatisPlusTest {
  5. @Autowired
  6. private CompanyMapper companyMapper;
  7. @Test
  8. public void insertTest(){
  9. Company company = new Company();
  10. company.setName("阿里");
  11. company.setContact("张三");
  12. company.setContactType("17683723698");
  13. company.setCreateTime(System.currentTimeMillis());
  14. company.setRemoved(0);
  15. companyMapper.insert(company);
  16. }
  17. }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xLToAcDp-在这里插入图片描述

更新

  1. int updateById(@Param("et") T entity);
  2. int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
根据id进行更新
  1. @Test
  2. public void updateTest1(){
  3. Company company = new Company();
  4. company.setId(6);
  5. company.setName("阿里");
  6. company.setContact("张三111");
  7. company.setContactType("17683723698");
  8. company.setCreateTime(System.currentTimeMillis());
  9. company.setRemoved(0);
  10. companyMapper.updateById(company);
  11. }

在这里插入图片描述

根据条件更新update

第一种

  1. @Test
  2. public void updateTest2(){
  3. //第一种
  4. Company company = new Company();
  5. company.setContact("张三222"); //需要更新的字段
  6. //queryWrapper对象,用于设置条件
  7. QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
  8. queryWrapper.eq("id",6);//设置查询条件
  9. companyMapper.update(company,queryWrapper);
  10. }

在这里插入图片描述

第二种:推荐

  1. @Test
  2. public void updateTest3(){
  3. //UpdateWrapper更新操作
  4. UpdateWrapper<Company> warp = new UpdateWrapper<>();
  5. //通过set设置需要修改的内容,eq设置条件
  6. warp.set("name","阿里111").set("contact","zhansgan3333").eq("id",6);
  7. companyMapper.update(null,warp);
  8. }

在这里插入图片描述

查询

  1. T selectById(Serializable id);
  2. List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
  3. List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
  4. T selectOne(@Param("ew") Wrapper<T> queryWrapper);
  5. Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
  6. List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
  7. @Test
  8. public void selectTest(){
  9. //根据id查询
  10. Company company = companyMapper.selectById(6);
  11. System.out.println(company);
  12. //根据id集合查询
  13. List<Company> companyList = companyMapper.selectBatchIds(ListUtil.of(6, 5, 4));
  14. System.out.println(companyList);
  15. //根据条件查询一个
  16. QueryWrapper<Company> query = new QueryWrapper<>();
  17. query.eq("name","华为");
  18. Company company1 = companyMapper.selectOne(query);
  19. System.out.println(company1);
  20. //根据map查询
  21. Map<String, Object> map = new HashMap<>();
  22. map.put("contact","张三");
  23. List<Company> companyList1 = companyMapper.selectByMap(map);
  24. System.out.println(companyList1);
  25. //根据条件查询个数
  26. QueryWrapper<Company> query1 = new QueryWrapper<>();
  27. query1.eq("contact","张三");
  28. Integer integer = companyMapper.selectCount(query1);
  29. System.out.println(integer);
  30. //根据条件查询多个
  31. List<Company> companyList2 = companyMapper.selectList(query1);
  32. System.out.println(companyList2);
  33. }

分页查询

  1. <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);
不带条件的分页查询

在这里插入图片描述

带条件的分页查询
  1. @Test
  2. public void pageTest2(){
  3. IPage<Company> page = new Page<>(1, 2);
  4. QueryWrapper<Company> query = new QueryWrapper<>();
  5. query.eq("name","华为");
  6. IPage<Company> companyIPage = companyMapper.selectPage(page, query);
  7. System.out.println(companyIPage);
  8. }

删除

  1. int deleteById(Serializable id);
  2. int deleteByMap(@Param("cm") Map<String, Object> columnMap);
  3. int delete(@Param("ew") Wrapper<T> queryWrapper);
  4. int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
  5. @Test
  6. public void deleteTest2() {
  7. companyMapper.deleteById(6);
  8. Map<String, Object> map = new HashMap<>();
  9. map.put("contact", "李四");
  10. companyMapper.deleteByMap(map);
  11. QueryWrapper<Company> query = new QueryWrapper<>();
  12. query.eq("name", "迈异2");
  13. companyMapper.delete(query);
  14. companyMapper.deleteBatchIds(ListUtil.of(4));
  15. }

三、逻辑删除配置

在这里插入图片描述

在这里插入图片描述

  1. @Test
  2. public void deleteTest2() {
  3. companyMapper.deleteById(2);
  4. }

这里可以看到已经逻辑删除成功

四、自动填充配置

自定义填充类

  1. package com.mye.cloudboxdcim.framework.engine.mybatisplus;
  2. import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.ibatis.reflection.MetaObject;
  5. import org.springframework.stereotype.Component;
  6. @Slf4j
  7. @Component
  8. public class MyMetaObjectHandler implements MetaObjectHandler {
  9. @Override
  10. public void insertFill(MetaObject metaObject) {
  11. this.strictInsertFill(metaObject, "createTime", Long.class, System.currentTimeMillis()); // 起始版本 3.3.0(推荐使用)
  12. }
  13. @Override
  14. public void updateFill(MetaObject metaObject) {
  15. this.strictUpdateFill(metaObject, "updateTime",Long.class, System.currentTimeMillis()); // 起始版本 3.3.0(推荐)
  16. }
  17. }

配置自定义填充

在这里插入图片描述

在实体类上添加注释

  1. public class Company {
  2. /**
  3. * 创建时间
  4. */
  5. @TableField(fill = FieldFill.INSERT)
  6. private Long createTime;
  7. /**
  8. * 修改时间
  9. */
  10. @TableField(fill = FieldFill.UPDATE)
  11. private Long updateTime;
  12. }

注意

  • 填充原理是直接给entity的属性设置值
  • 注解则是指定该属性在对应情况下必有值,如果无值则入库会是null
  • MetaObjectHandler提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null则不填充
  • 字段必须声明TableField注解,属性fill选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
  • 填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component@Bean注入
  • update(T t,Wrapper updateWrapper)时t不能为空,否则自动填充失效

五、主键配置

自 3.3.0 开始,默认使用雪花算法+UUID(不含中划线)

字段上使用注释

在每一个实体类的id上添加注释

  1. @TableId(value = "id",type = IdType.AUTO)
  2. private Integer id;

配置全局主键自增

  1. GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
  2. /* id自增 */
  3. dbConfig.setIdType(IdType.AUTO);

六、注解

@TableName

表名注解,标识实体类对应的表

  1. @TableName("sys_user")
  2. public class User {
  3. private Long id;
  4. private String name;
  5. private Integer age;
  6. private String email;
  7. }

@TableId

主键注解,实体类主键字段

value 是主键字段名,type 是指定主键类型,默认值为 IdType.NONE

  1. @TableId(value = "id",type = IdType.AUTO)
  2. private Integer id;





























描述
AUTO 数据库 ID 自增
NONE 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUT insert 前自行 set 主键值
ASSIGN_ID 分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID 分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)

@TableField

字段注解(非主键)

  1. // 指定数据库字段名
  2. @TableField(value = "name")
  3. private String name;
  4. // 指定自动填充类型
  5. @TableField(fill = FieldFill.INSERT)
  6. private Long createTime;

发表评论

表情:
评论列表 (有 0 条评论,16人围观)

还没有评论,来说两句吧...

相关阅读