MyBatis-Plus——逆向工程之AutoGenerator代码生成器

news/2024/7/6 3:08:54

1.案例详解

首先在Navicat中创建一张表。

创建一个SpringBoot项目,在pom文件中添加相关依赖。

大部分依赖我们都是见过的,因为这里需要使用MP框架中的逆向工程生成代码,所以还需要一个模板引擎依赖。

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.9</version>
        </dependency>

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

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

在核心配置文件中添加数据库连接的相关信息。

#配置数据库的相关连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=12345678

#配置对应的日志信息
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

编写代码生成的核心类。

package com.szh.mybatisplus;


import com.baomidou.mybatisplus.annotation.IdType;
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 AutoMapper {

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

        //设置全局配置
        GlobalConfig gc=new GlobalConfig();
        //设置代码的生成位置(磁盘目录)
        String path=System.getProperty("user.dir");
        gc.setOutputDir(path + "/02-end/src/main/java");
        //设置生成的作者
        gc.setAuthor("张起灵-小哥");
        //设置生成的类名
        gc.setMapperName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        //设置主键id的配置
        gc.setIdType(IdType.AUTO);
        //将全局配置信息提交给代码生成器
        ag.setGlobalConfig(gc);

        //设置数据源DataSource
        DataSourceConfig ds=new DataSourceConfig();
        ds.setDriverName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8");
        ds.setUsername("root");
        ds.setPassword("12345678");
        //将数据源信息提交给代码生成器
        ag.setDataSource(ds);

        //设置Package包
        PackageConfig pc=new PackageConfig();
        //设置生成的父级包、当前包
        pc.setModuleName("exam");
        pc.setParent("com.szh.mybatisplus");
        //将包信息提交给代码生成器
        ag.setPackageInfo(pc);

        //设置策略信息
        StrategyConfig sc=new StrategyConfig();
        //设置数据库表的命名规则:支持驼峰命名法
        sc.setNaming(NamingStrategy.underline_to_camel);
        //设置数据库表中字段的命名规则,支持驼峰命名法
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        //将策略信息提交给代码生成器
        ag.setStrategy(sc);

        //执行代码的生成
        ag.execute();
    }
}

运行上面这个核心主类。即可自动生成如下代码:👇👇👇

这里之所以生成了两个实体类,是因为我连接的数据库是springdb,在这个数据库中有两张表。

在编写测试代码之前,要记着在SpringBoot项目的启动入口类上,添加@MapperScan注解。

package com.szh.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.szh.mybatisplus.exam")
public class Application {

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

}

编写几个测试方法,测试一下我们生成的代码是否可以正常运行。(首先将需要用到的mapper接口注入到Spring容器中)

@Resource
private StudentMapper studentMapper;
    @Test
    void testInsertStudent() {
        Student student = new Student();
        student.setName("张起灵");
        student.setAge(18);
        student.setEmail("zql@sina.com");
        student.setStatus(1);

        int rows=studentMapper.insert(student);
        System.out.println("insert的结果:" + rows);
    }

    @Test
    void testSelectStudentById() {
        Student student=studentMapper.selectById(7);
        System.out.println("select的结果:" + student);
    }

    @Test
    void testSelectStudent() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        qw.lt("age",25);
        qw.isNotNull("email");

        List<Student> studentList=studentMapper.selectList(qw);
        for (Student stu : studentList) {
            System.out.println("select的结果:" + stu);
        }
    }


http://www.niftyadmin.cn/n/711402.html

相关文章

黑马程序员—11-oc初认识

------- android培训、java培训、期待与您交流&#xff01; ---------- 一、 OC简介 C语言的基础上&#xff0c;增加了一层最小的面向对象语法 完全兼容C语言 可以在OC代码中混入C语言代码&#xff0c;甚至是C代码 可以使用OC开发Mac OS X平台和iOS平台的应用程序…

创建dynamics CRM client-side (七) - 用JS 来控制Auto-Save

在我们的system setting里面&#xff0c; 我们可以设置打开/关闭 auto save的功能。 我们可以用js来控制auto-save this.formOnSave function (executionContext) {var eventArgs executionContext.getEventArgs();if (eventArgs.getSaveMode() 70 || eventArgs.getSaveMode…

计算机硬件系统方案表,基于EDA技术的计算机硬件系统设计方案

1引言随着计算机技术的迅速发展&#xff0c;计算机系统中使用的硬件部件基本上都采用大规模和超大规模集成电路&#xff0c;这些电路的设计、验证和测试必须使用先进的工具软件&#xff0c;使硬件设计逐渐趋于软件化&#xff0c;加快硬件设计和调试的速度&#xff0c;计算机硬件…

cocos2d JS-(JavaScript) 静态方法的例子

1 function User(name, age) {2 this.name name;3 this.age age;4 }5 var user new User(angela,26);6 7 User.cloneUser function (user) {//静态方法8 return new User(user.name, user.age);//创建…

CentOS下date命令 - 显示和设置系统日期与时间

显示系统日期 要显示系统日期,只要输入: $ date Thu Dec 5 22:55:41 WIB 2013 格式化显示日期 日期有很多格式。如果你不喜欢默认的格式&#xff0c;你可以换一种格式。你可能会想"为什么我需要改变格式? 默认的输出对我足够了。" 是的&#xff0c;你说的对&#xf…

iframe 父子间传值通信

1、同域 iframe 父子间传值 &#xff08;1&#xff09;父页面 <html> <head><script type"text/javascript">function say(){alert("parent.html");}function callChild(){myFrame.window.say();myFrame.window.document.getElementById…

spring mvc MultipartHttpServletRequest获取页面传入的所有文件

2019独角兽企业重金招聘Python工程师标准>>> 用MultipartHttpServletRequest multipartRequest (MultipartHttpServletRequest) request; 可获取所有页面传入的文件 RequestMapping(value"/shenbao_submit")public ModelAndView shenbao_submit(HttpServ…

计算机病毒的运营消耗cpu,工业计算机CPU使用率过高的原因以及解决方法

原标题&#xff1a;工业计算机CPU使用率过高的原因以及解决方法当工业计算机CPU使用率过高&#xff0c;导致资源不足时&#xff0c;很容易会出现卡死或者长时间等待无响应的情况。这时候我们只能通过手动的方式让工业计算机实现重启&#xff0c;但是如果之前运行的一些数据都没…