SpringBoot极速整合MyBatis-Plus

本文涉及的产品
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS AI 助手,专业版
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
简介: MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

@[Toc]

一、MyBatis-Plus简介

MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

在这里插入图片描述

MyBatis-Plus具有如下特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
    -支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

    • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
    • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

      • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
    • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
    • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
    • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
    • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
    • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
官网地址: https://baomidou.com/


二、基本用法

1、准备数据

我们这里使用MySQL数据库,先准备好相关数据

表结构:其中种类和产品是一对多的关系
在这里插入图片描述

建表语句:

DROP TABLE IF EXISTS `category`;
CREATE TABLE `category`  (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '种类表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `category_id` int(11) NOT NULL,
  `price` decimal(10, 2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;


2、引入依赖

通过开发工具创建一个SpringBoot项目(版本为2.4.0),引入以下依赖:

        <!--mybatis-plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>


2、配置

在配置文件里写入相关配置:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

@SpringBootApplication
@MapperScan("cn.fighter3.mapper")
public class SpringbootMybatisPlusApplication {

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

}


3、代码

  • 实体类
/**
 * @Author 三分恶
 * @Date 2020/11/14
 * @Description 产品实体类
 */
@TableName(value = "product")
public class Product {
    @TableId(type = IdType.AUTO)
    private Long pid;
    private String productName;
    private Long categoryId;
    private Double price;
    //省略getter、setter
}
  • Mapper接口:继承BaseMapper即可
/**
 * @Author 三分恶
 * @Date 2020/11/14
 * @Description
 */
public interface ProductMapper extends BaseMapper<Product> {
}


4、测试

  • 添加测试类
@SpringBootTest
class SpringbootMybatisPlusApplicationTests {
}
  • 插入
    @Test
    @DisplayName("插入数据")
    public void testInsert(){
        Product product=new Product();
        product.setProductName("小米10");
        product.setCategoryId(1l);
        product.setPrice(3020.56);
        Integer id=productMapper.insert(product);
        System.out.println(id);
    }
  • 根据id查找
    @Test
    @DisplayName("根据id查找")
    public void testSelectById(){
        Product product=productMapper.selectById(1l);
        System.out.println(product.toString());
    }
  • 查找所有
    @Test
    @DisplayName("查找所有")
    public void testSelect(){
       List productList=productMapper.selectObjs(null);
        System.out.println(productList);
    }
  • 更新
    @Test
    @DisplayName("更新")
    public void testUpdate(){
        Product product=new Product();
        product.setPid(1l);
        product.setPrice(3688.00);
        productMapper.updateById(product);
    }
  • 删除
    @Test
    @DisplayName("删除")
    public void testDelete(){
        productMapper.deleteById(1l);
    }


三、自定义SQL

使用MyBatis的主要原因是因为MyBatis的灵活,mp既然是只对MyBatis增强,那么自然也是支持以Mybatis的方式自定义sql的。

  • 修改pom.xml,在 \<build>中添加:
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
  • 配置文件:添加mapper扫描路径及实体类别名包
mybatis.mapper-locations=classpath:cn/fighter3/mapper/*.xml
mybatis.type-aliases-package=cn.fighter3.model


1、自定义批量插入

批量插入是比较常用的插入,BaseMapper中并没有默认实现,在com.baomidou.mybatisplus.service.IService中虽然实现了,但是是一个循环的插入。

所以用Mybatis的方式自定义一个:

  • 在ProductMapper同级路径下新建ProductMapper:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.fighter3.mapper.ProductMapper">

</mapper>
  • 在接口里定义批量插入方法
public interface ProductMapper extends BaseMapper<Product> {
    void batchInsert(@Param("productList") List<Product> productList);
}
  • 编写批量插入xml脚本
    <insert id="batchInsert">
        insert into product (product_name,category_id,price)
        values
        <foreach collection="productList" item="product" separator=",">
            (#{product.productName},#{product.categoryId},#{product.price})
        </foreach>
    </insert>
  • 测试
    @Test
    public void testBatchInsert(){
        List<Product> productList=new ArrayList<>();
        productList.add(new Product("小米10",1l,3020.56));
        productList.add(new Product("Apple iPhone 11",1l,4999.00));
        productList.add(new Product("Redmi 8A",1l,699.00));
        productList.add(new Product("华为 HUAWEI nova 5z",1l,1599.00));
        productList.add(new Product("OPPO A52",1l,1399.00));
        productMapper.batchInsert(productList);
    }


2、自定义查询

基本的Mybatis方式的查询这里就不再展示了,参照Mybatis的即可。

MP提供了一种比较方便的查询参数返回和查询条件参数传入的机制。


2.1、自定义返回结果

Mybatis Plus接口里定义的查询是可以直接以map的形式返回。

  • 定义:定义了一个方法,返回用的是map
    /**
     * 返回带分类的产品
     * @return
     */
    List<Map> selectProductWithCategory();
  • 查询脚本:查询字段有pid、product_name、category_name、price
    <select id="selectProductWithCategory" resultType="map">
      select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
   </select>
  • 测试:
    @Test
    @DisplayName("自定义返回结果")
    public void testsSlectProductWithCategory(){
        List<Map> productList=productMapper.selectProductWithCategory();
        productList.stream().forEach(item->{
            System.out.println(item.toString());
        });
    }
  • 结果:

在这里插入图片描述


2.2、自定义查询条件参数

除了返回结果可以使用map,查询用的参数同样可以用map来传入。

  • 定义:
    List<Map> selectProductWithCategoryByMap(Map<String,Object> map);
  • 查询脚本:
    <select id="selectProductWithCategoryByMap" resultType="map" parameterType="map">
      select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
      <where>
          <if test="categoryId !=null and categoryId !=''">
              and p.category_id=#{categoryId}
          </if>
          <if test="pid !=null and pid !=''">
              and p.pid=#{pid}
          </if>
      </where>
   </select>
  • 测试:
    @Test
    @DisplayName("自定义返回结果有入参")
    public void testSelectProductWithCategoryByMap(){
        Map<String,Object> params=new HashMap<>(4);
        params.put("categoryId",1l);
        params.put("pid",5);
        List<Map> productList=productMapper.selectProductWithCategoryByMap(params);
        productList.stream().forEach(item->{
            System.out.println(item.toString());
        });
    }
  • 结果:

在这里插入图片描述


2.3、map转驼峰

上面查询结果可以看到,返回的确实是map,没有问题,但java类中的驼峰没有转回来呀,这样就不友好了。

只需要一个配置就能解决这个问题。

创建 MybatisPlusConfig.java 配置类,添加上下面配置即可实现map转驼峰功能。

/**
 * @Author 三分恶
 * @Date 2020/11/16
 * @Description
 */
@Configuration
@MapperScan("cn.fighter.mapper")
public class MybatisPlusConfig {
    @Bean("mybatisSqlSession")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        //*注册Map 下划线转驼峰*
        configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());

        // 添加数据源
        sqlSessionFactory.setDataSource(dataSource);

        sqlSessionFactory.setConfiguration(configuration);

        return sqlSessionFactory.getObject();
    }
}

再次运行之前的单元测试,结果:

在这里插入图片描述

OK,下划线已经转驼峰了。


3、自定义一对多查询

在实际应用中我们常常需要用到级联查询等查询,可以采用Mybatis的方式来实现。


3.1、 Category相关

category和product是一对多的关系,我们这里先把category表相关的基本实体、接口等编写出来。

  • Category.java
/**
 * @Author 三分恶
 * @Date 2020/11/15
 * @Description
 */
@TableName(value = "category")
public class Category {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String categoryName;
    private List<Product> productList;
    //省略getter、setter等
}
  • CategoryMapper.java
/**
 * @Author 三分恶
 * @Date 2020/11/15
 * @Description
 */
public interface CategoryMapper extends BaseMapper<Category> {
}
  • CategoryMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.fighter3.mapper.CategoryMapper">

</mapper>

直接向数据库中插入数据:

INSERT into category(category_name) VALUE ('手机');


3.2、自定义返回结果

自定义返回结果map:

    <!--自定义返回列-->
    <resultMap id="categoryAndProduct" type="cn.fighter3.model.Category">
        <id column="cid" property="cid" />
        <result column="category_name" property="categoryName" />
        <!--一对多关系-->
        <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
        <collection property="productList" ofType="cn.fighter3.model.Product">
            <id column="pid" property="pid" />
            <result column="product_name" property="productName" />
            <result column="category_id" property="categoryId" />
            <result column="price" property="price" />
        </collection>
    </resultMap>


3.3、自定义一对多查询

  • 先定义方法
public interface CategoryMapper extends BaseMapper<Category> {
    List<Category> selectCategoryAndProduct(Long id);
}
  • 查询脚本
    <!--查询分类下的产品-->
    <select id="selectCategoryAndProduct" resultMap="categoryAndProduct" parameterType="java.lang.Long">
       select c.*,p.* from category c left join product p on c.cid=p.category_id
       <if test="id !=null and id !=''">
           where c.cid=#{id}
       </if>
    </select>
  • 测试
    @Test
    public void testSelectCategoryAndProduct(){
        List<Category> categoryList=categoryMapper.selectCategoryAndProduct(null);
        categoryList.stream().forEach(i->{
           i.getProductList().stream().forEach(product -> System.out.println(product.getProductName()));
        });
    }

Mybatis方式的一对多查询就完成了。多对一、多对多查询这里就不再展示,参照Mybatis即可。


4、 分页查询

mp的分页查询有两种方式,BaseMapper分页和自定义查询分页。

4.1、BaseMapper分页

直接调用方法即可:

    @Test
    @DisplayName("分页查询")
    public void testSelectPage(){
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        IPage<Product> productIPage=new Page<>(0, 3);
        productIPage=productMapper.selectPage(productIPage,wrapper);
        System.out.println(productIPage.getRecords().toString());
    }


4.2、自定义分页查询

  • 在前面写的MybatisPlusConfig.java 配置类sqlSessionFactory方法中添加分页插件:
        //添加分页插件
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        sqlSessionFactory.setPlugins(new Interceptor[]{paginationInterceptor});
  • 定义方法
    IPage<Map> selectProductMapWithPage(IPage iPage);
  • 查询脚本
    <select id="selectProductMapWithPage" resultType="map">
      select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
   </select>
  • 测试
    @Test
    @DisplayName("自定义分页查询")
    public void testSelectProductMapWithPage(){
        Integer pageNo=0;
        Integer pageSize=2;
        IPage<Map> iPage = new Page<>(pageNo, pageSize);
        iPage=productMapper.selectProductMapWithPage(iPage);
        iPage.getRecords().stream().forEach(item->{
            System.out.println(item.toString());
        });
    }
  • 结果

在这里插入图片描述

这里有几点需要注意:

  1. 在xml文件里写的sql语句不要在最后带上;,因为有些分页查询会自动拼上 limit 0, 10; 这样的sql语句,如果你在定义sql的时候已经加上了 ;,调用这个查询的时候就会报错了
  1. 往xml文件里的查询方法里传参数要带上 @Param("") 注解,这样mybatis才认,否则会报错
  2. 分页中传的pageNo可以从0或者1开始,查询出的结果是一样的,这一点不像jpa里必须是从0开始才是第一页


四、代码生成器

相信用过Mybatis的开发应该都用过Mybatis Gernerator,这种代码自动生成插件大大减少了我等crud仔的重复工作。MP同样提供了代码生成器的功能。

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。


1、引入依赖

在原来项目的基础上,添加如下依赖。

  • MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
        <!--代码生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
  • 添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足要求,可以采用自定义模板引擎。

Velocity(默认):

        <!--模板引擎依赖,即使不需要生成模板,也需要引入-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
  • 其它依赖
        <!--会生成Controller层,所以引入-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--代码生成器中用到了工具类-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>

2、代码生成

下面这个类是代码生成的一个示例。因为在前后端分离的趋势下,实际上我们已经很少用模板引擎了,所以这里没有做模板引擎生成的相关配置。

public class MySQLCodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = "D:\\IdeaProjects\\dairly-learn\\springboot-mybatis-plus";
        //输出目录
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("三分恶");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("cn.fighter3");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };


        ///策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(false);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        //strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.execute();
    }

}


  • 运行该类,运行结果如下

在这里插入图片描述

  • 生成的代码如下:

在这里插入图片描述

已经生成了基本的三层结构。在数据库字段比较多的情况下,还是能减少很多工作量的。

具体更多配置可查看官方文档 参考【8】。




本文为学习笔记,参考如下!
【1】:[MyBatis-Plus简介](https://baomidou.com/guide/#%E7%89%B9%E6%80%A7) 【2】:[Spring Boot 2 (十一):如何优雅的使用 MyBatis 之 MyBatis-Plus](http://www.ityouknow.com/springboot/2019/05/14/spring-boot-mybatis-plus.html) 【3】:[最全的Spring-Boot集成Mybatis-Plus教程](https://tomoya92.github.io/2019/04/15/spring-boot-mybatis-plus-tutorial/) 【4】:[整合:SpringBoot+Mybatis-plus](https://blog.nowcoder.net/n/b27288e38c6b4a07a536afc3ceac0523) 【5】:[一起来学SpringBoot(十五)MybatisPlus的整合](https://www.fulinlin.com/2019/07/25/yuque/%E4%B8%80%E8%B5%B7%E6%9D%A5%E5%AD%A6SpringBoot%EF%BC%88%E5%8D%81%E4%BA%94%EF%BC%89MybatisPlus%E7%9A%84%E6%95%B4%E5%90%88/#Sql%E6%89%A7%E8%A1%8C%E5%88%86%E6%9E%90%E6%8F%92%E4%BB%B6) 【6】:[整合:SpringBoot+Mybatis-plus](https://blog.nowcoder.net/n/b27288e38c6b4a07a536afc3ceac0523) 【7】:[MyBatis-Plus – 批量插入、更新、删除、查询](https://www.codenong.com/cs106800198/) 【8】:[MyBatis-Plus 代码生成器配置](https://baomidou.com/config/generator-config.html#baseresultmap)
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
12月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
751 0
|
9月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1463 1
Spring boot 使用mybatis generator 自动生成代码插件
|
9月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
357 1
|
8月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
231 0
|
9月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
488 1
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
796 29
|
12月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
903 0
|
12月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1711 0
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
2907 11
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
679 2