侧边栏壁纸
博主头像
coydone博主等级

记录学习,分享生活的个人站点

  • 累计撰写 306 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Mybatis逆向工程

coydone
2022-03-10 / 0 评论 / 0 点赞 / 349 阅读 / 6,983 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

概述

所谓Mybatis逆向工程,就是Mybatis会根据我们设计好的数据表,自动生成pojo、mapper、mapper.xml以及example类(用于添加条件,相当where语句后面的部分),我们在开发的过程操作多个表,一个个去写pojo类就已经够麻烦了。通过Mybatis逆向工程可以把基本的配置自动完成,省了许多事,当然自动生成的代码通常与业务相差甚远,我基本用来生成pojo类,也可以都生成,根据自己需要进行选择。

Generator

MyBatis Generator(MBG)是MyBatis的代码生成器。它将为所有版本的MyBatis以及2.2.0之后的iBATIS版本生成代码。这将减少在设置对象、配置文件以及数据库表交互方面的麻烦。MBG寻求对数据库进行简单的CRUD(增,查,改,删)操作,但仍需要为连接查询或存储过程手动编写SQL和对象代码。简单来说,它会自动帮我们生成实体类、接口、SQL映射文件。

实现逆向工程

1、添加依赖

在pom.xml文件中添加Generator的依赖环境。

<dependencies>
    <!-- MySQL依赖-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <!-- 加入MyBatis 依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <!--mybatis自动生成jar包-->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.7</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
<build>
    <!--配置相关的资源进行打包-->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

2、编写generator.xml

在main/java/resources下新建generator.xml。

需要使用本地的一个数据库连接包mysql-connector-java-5.1.0-bin.jar,用于连接数据库通过数据库字段生成实体和简单的CRUD映射。

创建项目的目录结构,在main.java下创建如com.coydone.entity(实体类)、mapper(映射类)、utils(工具类)、ui(测试类)包结构。

<?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>
    <!--指定数据的驱动包-->
    <classPathEntry location="D:\mysql-connector-java-5.1.0-bin.jar" />

    <context id="Mysql2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"></property>
            <property name="suppressAllComments" value="true"></property>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/testdb"
                        userId="root"
                        password="root123">
        </jdbcConnection>
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        
        <!--指定生成实体所有在的包	targetProject如果为项目下的模块,要加上模块名-->
        <javaModelGenerator targetPackage="com.coydone.entity" targetProject="day04_mybatis/src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        
        <!--指定sql映射文件的位置-->
        <sqlMapGenerator targetPackage="com.coydone.mapper" targetProject="day04_mybatis/src/main/java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        
        <!--指定接口存放的位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.coydone.mapper" targetProject="day04_mybatis/src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        
         <!--添加需要反向工程的表 设置为true表示加入某个功能-->
        <table  tableName="grade" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
        </table>
        <table  tableName="student" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

3、运行MybatisGeneratorUtil工具类

package com.coydone.utils;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MybatisGeneratorUtil {

   public static void main(String[] args) {
      try {
         System.out.println("start generator ...");
         List<String> warnings = new ArrayList<String>();
         boolean overwrite = true;
          //如果想对路径有问题,则使用generator.xml在硬盘上的绝对路径
         //File configFile = new File(MybatisGeneratorUtil.class.getResource("/generator.xml").getFile());
         File configFile = new File("E:\\javaSE\\idea\\Installation Path\\idea_workspace\\u3_ssm\\day04_mybatis\\src\\main\\resources\\generator.xml");
         ConfigurationParser cp = new ConfigurationParser(warnings);
         Configuration config = cp.parseConfiguration(configFile);
         DefaultShellCallback callback = new DefaultShellCallback(overwrite);
         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
         myBatisGenerator.generate(null);
         System.out.println("end generator!");
      } catch (IOException e) {
         e.printStackTrace();
      } catch (XMLParserException e) {
         e.printStackTrace();
      } catch (InvalidConfigurationException e) {
         e.printStackTrace();
      } catch (SQLException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }
}

实现效果

注意:逆向工程生成代码之后,这些逆向工程所需的依赖和工具类都可以进行删除,它只是帮助我们简化Mybatis开发,在项目运行时不需要。

测试

以学生类为例,我们可以看见,在StudentMapper.java中,它帮助我们生成了基本的CURD方法。

public interface StudentMapper {
    int deleteByPrimaryKey(Integer xh);

    int insert(Student record);

    int insertSelective(Student record);

    List<Student> selectByExample(StudentExample example);

    Student selectByPrimaryKey(Integer xh);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

我们可以用逆向工程生成的StudentExample来做条件查询。调用StudentMapper中的selectByExample()方法。

public class StudentTest {
    StudentMapper studentMapper = MyBatisUtil.getSession().getMapper(StudentMapper.class);
    //条件查询20-50岁
    @Test
    public void findAllByExample(){
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        StudentExample.Criteria ageBetween = criteria.andAgeBetween(new Byte("20"), new Byte("50"));
        List<Student> students = studentMapper.selectByExample(studentExample);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Student student : students) {   
            String birthday = sdf.format(student.getBirthday());
            System.out.println(student);
            System.out.println(birthday);
        }
    }
}
0

评论区