IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Mybatis-plus -> 正文阅读

[Java知识库]Mybatis-plus

Mybatis-plus

为了简化mybatis开发而设计,对mybatis只做增强而不做改变

特性

  • 无侵入:在项目中引入不会对现有项目产生影响
  • 损耗小:启动即会自动自动注入基本的curd,
  • 强大的crud操作:内置mapper,通过Service,仅仅使用少量配置即可完成简单的crud操作
  • 支持lambda形式调用:可通过lambda表达式编写各种查询条件
  • 支持主键自动生成
  • 支持ActiveRecord模式:支持ActiveRecord形式调用,
  • 支持自定义全局通用操作
  • 内置代码生成器
  • 内置分页插件:可基于mybatis物理分页
  • 分页插件支持多种数据库
  • 提供全局拦截器

jar包引入

spring-boot
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

spring MVC

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.5.2</version>
</dependency>
补充:mybatis-plus和mybatis两者会存在版本冲突问题

项目示例(Spring boot)

  1. 相关操作

    • jar包引入

    • 配置数据源

      • spring:
          application:
            name: demo
          datasource:
            username: root
            password: 411624
            url: jdbc:mysql://127.0.0.1:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
        
    • 配置mybatis-plus使用的日志

      • mybatis-plus:
          configuration:
            log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        
    • 创建package用于存放相关mapper文件,并在启动类上添加注解@MapperScan(“package location”)

    • 让创建的mapper(接口)文件继承BaseMapper抽象类

  2. 相关注解

    1. @TableName(“str”) -->str为数据库中表名称
    2. @TableId() —>被修饰对象视为表中的主键
    3. @TableField() —>被修饰对象为表中非主键属性
  3. mapper中可使用的方法

    1. int insert(T entity)  
      
    2. int deleteById(Serializable id);
      
    3. //通过实体id产出表中记录
      int deleteById(T entity);
      
    4. //通过columnMap参数产出相关记录
      int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
      
      • eg:

        @Test
            public void test03() {
        
                Map<String, Object> columnMap = new HashMap<String, Object>();
                columnMap.put("email","23@qq.com");
                columnMap.put("age",30);
                int i = userMapper.deleteByMap(columnMap);
                System.out.println(i);
            }
        
    5. //
      int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
    6. int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
      
      • public void test05() {
                int i = userMapper.deleteBatchIds(Arrays.asList(2L,3L));
                System.out.println(i);
            }
        
    7. int updateById(@Param(Constants.ENTITY) T entity);
      
    8. int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
      
    9. List<T> selectBatchIds(@Param(Constants.COLL) Collection<? extends Serializable> idList);
      
    10. List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
      
    11. default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
          List<T> ts = this.selectList(queryWrapper);
          if (CollectionUtils.isNotEmpty(ts)) {
              if (ts.size() != 1) {
                  throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
              }
              return ts.get(0);
          }
          return null;
      }
      
    12. default boolean exists(Wrapper<T> queryWrapper) {
          Long count = this.selectCount(queryWrapper);
          return null != count && count > 0;
      }
      
    13. Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
      
    14. List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
    15. List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
    16. List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
    17. <P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
    18. <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
      
      有关QueryWrapper的使用
      • 声明实体类

        • QueryWrapper<Users> queryWrap = new QueryWrapper<>();
          
          相关方法声明
          • allEq,eq(select),ne(!=),gt(>),ge(>=),It(<),le(<=),between,notBetween,like,notLike,likeLeft,liekRight,isNull,isNotNull,in,notIn,isSql,notInSql,groupBy,orderByAsc,orderByDesc,orderBy,having,func,or,and,nested,apply,last,exists,notExists,QueryWrapper,select,UpdateWrapper,set,setSql,lambda

代码生成器

添加依赖
		<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>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--模板引擎依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

		<!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
代码构造器逻辑编写
 		// 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("Nero");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setSwagger2(true);//开启Swagger2模式
        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/financial?				serverTimezone=GMT%2B8&characterEncoding=utf-8");  //自己的数据库名称
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("******");   //自己数据库连接密码
        dsc.setDbType(DbType.MYSQL);  //数据库类型
        mpg.setDataSource(dsc);   

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.demo");
        pc.setEntity("pojo"); //此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象。
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok
        strategy.setLogicDeleteFieldName("is_deleted");//逻辑删除字段名
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//去掉布尔值的is_前缀(确保tinyint(1))
        strategy.setRestControllerStyle(true); //restful api风格控制器
        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
补充:AutoGenerator中共配置的GlobalConfig,DataSourceConfig,PackageConfig,StrategyConfig属性其他配置客通过查看源代码进行选择配置
配置文件编写
server:
  port: 8080

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: ******
    url: jdbc:mysql://localhost:3306/financial?serverTimezone=GMT%2B8&characterEncoding=utf-8
mybatis-plus:
  mapper-locations: classpath*:com/example/demo/mapper/xml/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

在启动类中添加MapperScann()注解
@MapperScan("com.example.demo.mapper")
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-09-30 00:38:26  更:2022-09-30 00:42:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年3日历 -2025/3/10 15:49:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码