首页 > 其他分享 >12. MyBatis的逆向工程

12. MyBatis的逆向工程

时间:2022-10-22 15:35:27浏览次数:29  
标签:逆向 12 mapper -- StudentMapper sqlSession org MyBatis import

一、什么是MyBatis逆向工程

  正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。 Hibernate是支持正向工程的。

  逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:Java实体类、Mapper接口、Mapper映射文件

二、创建逆向工程的步骤

数据的准备

CREATE DATABASE IF NOT EXISTS db_test;
USE db_test;

CREATE TABLE IF NOT EXISTS t_student(
	student_id BIGINT PRIMARY KEY auto_increment,
	name VARCHAR(20),
	age INT,
	sex CHAR,
	birth date,
	score DOUBLE
);

INSERT INTO t_student(name,age,sex,birth,score)
VALUES ('Sakura',10,'女','1987-04-01',95),
    ('Mikoto',14,'女','1995-05-02',100),
    ('Shana',15,'女',null,97);

添加依赖和插件

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
</dependencies>

<!-- 配置MyBatis逆向工程的插件-->
<build>
    <!-- 构建过程中用到的插件 -->
    <plugins>
        <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.0</version>

            <!-- 允许覆盖 -->
            <configuration>
                <overwrite>true</overwrite>
            </configuration>

            <!-- 插件的依赖 -->
            <dependencies>
                <!-- 逆向工程的核心依赖 -->
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.2</version>
                </dependency>

                <!-- MySQL驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.29</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

创建逆向工程的配置文件

  逆向工程的配置文件的文件名必须是:generatorConfig.xml,存放在类的根目录下。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "
        http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <!--
        targetRuntime: 执行生成的逆向工程的版本
            MyBatis3Simple: 生成基本的CRUD(清新简洁版)
            MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3">

        <commentGenerator>
            <!-- 是否去掉生成日期 -->
            <property name="suppressDate" value="true"></property>
            <!-- 是否去除注释 -->
            <property name="suppressAllComments" value="true"></property>
        </commentGenerator>

        <!-- 数据库的连接信息 -->
        <jdbcConnection
                driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/db_test"
                userId="root"
                password="abc123">
        </jdbcConnection>

        <!--
            javaBean的生成策略
                targetPackage:设置要生成的包目录
                targetProject:设置要生成在哪个项目中
        -->
        <javaModelGenerator targetPackage="star.light.pojo" targetProject=".\src\main\java">
            <!-- 设置是否能够使用子包 -->
            <property name="enableSubPackages" value="true" />
            <!-- 设置是否需要将数据库中字段前后的空格去掉,以便生成实体类的属性 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--
            SQL映射文件的生成策略
                targetPackage:设置要生成的包目录
                targetProject:设置要生成在哪个项目中
        -->
        <sqlMapGenerator targetPackage="star.light.mapper" targetProject=".\src\main\resources">
            <!-- 设置是否能够使用子包 -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--
            Mapper接口的生成策略
                targetPackage:设置要生成的包目录
                targetProject:设置要生成在哪个项目中
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="star.light.mapper" targetProject=".\src\main\java">
            <!-- 设置是否能够使用子包 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--
            逆向分析的表
            tableName设置为*号,可以对应所有表,此时不写domainObjectName
            domainObjectName属性指定生成出来的实体类的类名
        -->
        <table tableName="t_student" domainObjectName="Student"/>
    </context>
</generatorConfiguration>

执行插件的generate目标

3

运行结果

4

三、测试程序

导入jar包

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>

<!-- junit 测试程序 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

创建核心配置文件

  创建 MyBatis 的核心配置文件,习惯上命名为 mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。配置 MyBatis 的核心配置文件中的标签必须按照固定的顺序:

properties --> settings --> typeAliases --> typeHandlers --> objectFactory --> objectWrapperFactory --> reflectorFactory --> plugins --> environments --> databaseIdProvider --> mappers

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 引入数据库连接信息的配置文件 -->
    <properties resource="jdbc.properties"/>

    <!-- settings标签的内容是MyBatis极为重要的调整设置,它们会改变MyBatis的运行时行为 -->
    <settings>
        <!-- 指定MyBatis所有日志的具体实现,未指定时将自动查找 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
	<!-- 开启驼峰命名自动映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <!-- 将这个包下的所有的类全部起别名,别名就是类简名,不区分大小写 -->
        <package name="star.light.pojo"/>
    </typeAliases>

    <!-- environments:配置多个连接数据库环境 -->
    <environments default="development">
        <!-- environment:配置某个具体的环境 -->
        <environment id="development">
            <!-- 设置事务管理方式 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源 -->
            <dataSource type="POOLED">
                <!-- 设置连接数据库的驱动 -->
                <property name="driver" value="${jdbc.driver}"/>
                <!-- 设置连接数据库的地址 -->
                <property name="url" value="${jdbc.url}"/>
                <!-- 设置连接数据库的用户名 -->
                <property name="username" value="${jdbc.username}"/>
                <!-- 设置连接数据库的密码 -->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--引入映射文件-->
    <mappers>
        <!-- 从Mapper接口所在的包的路径中加载 -->
        <package name="star.light.mapper"/>
    </mappers>
</configuration>

  数据库连接信息的配置文件:jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test
jdbc.username=root
jdbc.password=abc123

封装SqlSessionUtil工具

package star.light.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SqlSessionUtil {
    private static SqlSessionFactory sqlSessionFactory;

    // 为了防止new对象,工具类的构造方法一般都是私有的
    // 工具类中所有的方法都是静态的,直接采用类型即可调用,不需要new对象
    private SqlSessionUtil(){}

    // 静态代码块在类加载的时候执行
    // SqlSesionUtil工具类在进行第一次加载的时候,解析MyBatis和核心配置文件,创建SqlSessionFactory对象
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取会话对象
     * @return 会话对象
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

测试程序

package star.light.test;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import star.light.mapper.StudentMapper;
import star.light.pojo.Student;
import star.light.pojo.StudentExample;
import star.light.util.SqlSessionUtil;

import java.util.List;

public class ReverseTest {

    @Test
    public void testDeletStudentByStudentId(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 根据主键删除
        int affectedRowCount = mapper.deleteByPrimaryKey(3L);
        System.out.println("affectedRowCount = " + affectedRowCount);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testSelectStudentByStudentId(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 根据主键查询
        Student student = mapper.selectByPrimaryKey(1L);
        System.out.println(student);
        sqlSession.close();
    }

    @Test
    public void testSelectAllStudent(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 根据条件查询,如果查询条件为null,表示没有条件
        List<Student> students = mapper.selectByExample(null);
        students.forEach(System.out::println);
        sqlSession.close();
    }

    @Test
    public void testSelectStudentByCriteria(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 封装条件,通过StudentExample封装条件
        StudentExample studentExample = new StudentExample();
        // 创建查询条件
        studentExample.createCriteria().andNameLike("Sakura").andSexEqualTo("女");
        // 添加or条件
        studentExample.or().andSexEqualTo("女").andAgeGreaterThan(10);
        // 根据条件进行查询
        List<Student> students = mapper.selectByExample(studentExample);
        students.forEach(System.out::println);
        sqlSession.close();
    }
}

标签:逆向,12,mapper,--,StudentMapper,sqlSession,org,MyBatis,import
From: https://www.cnblogs.com/nanoha/p/16816167.html

相关文章