Home  >  Article  >  Java  >  Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis reverse engineering

Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis reverse engineering

巴扎黑
巴扎黑Original
2017-06-26 09:34:552082browse

Please indicate the source for reprinting:

As mentioned earlier: Spring+SpringMVC+MyBatis in-depth learning and construction (9)-MyBatis and Spring integration

Use the mapper of the official website to automatically generate The tool mybatis-generator-core-1.3.2 is used to generate po classes and mapper mapping files.

1. What is reverse engineering

Mybatis requires programmers to write sql statements themselves. Mybatis officially provides reverse engineering that can automatically generate the code required for mybatis execution for a single table (mapper.java, mapper .xml, po...)

In actual enterprise development, the commonly used reverse engineering method is:

Generate java code from the database table.

2. Download the reverse engineering

#3. How to use (requires knowing how to use it)

In order to prevent later modification and expansion of the database table, Due to requirements modification and other reasons, the PO and mapper coverage automatically generated by the update are incorrect. We create a new specifically reverse-generated project generatorSqlmapCustom, and then copy the automatically generated po, ​​mapper, etc. to the project as required.

3.1 Run reverse engineering

It is recommended to use java program method without relying on development tools.

3.2mapper generation configuration file

Configure the detailed information of mapper generation in generatorConfig.xml, pay attention to the following points:

(1) Add the database table to be generated ;

(2) The package path where the po file is located;

(3) The package path where the mapper file is located.

The configuration file is as follows:

<?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><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- 是否去除自动生成的注释 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--数据库连接的信息:驱动类、连接地址、用户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatisdemo" userId="root"password=""></jdbcConnection><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
            userId="yycg"
            password="yycg">
        </jdbcConnection> --><!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject:生成PO类的位置 --><javaModelGenerator targetPackage="joanna.yan.po"targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /><!-- 从数据库返回的值被清理前后的空格 --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject:mapper映射文件生成的位置 --><sqlMapGenerator targetPackage="joanna.yan.mapper" 
            targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage:mapper接口生成的位置 --><javaClientGenerator type="XMLMAPPER"targetPackage="joanna.yan.mapper" 
            targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><p    roperty name="enableSubPackages" value="false" /></javaClientGenerator><!-- 指定数据库表 --><table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table><!-- <table schema="" tableName="sys_user"></table>
        <table schema="" tableName="sys_role"></table>
        <table schema="" tableName="sys_permission"></table>
        <table schema="" tableName="sys_user_role"></table>
        <table schema="" tableName="sys_role_permission"></table> --><!-- 有些表的字段需要指定java类型
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> --></context></generatorConfiguration>

3.3 Use Java class to generate mapper file

public class GeneratorSqlmap {public void generator() throws Exception{
        List<String> warnings = new ArrayList<String>();boolean overwrite = true;//指定 逆向工程配置文件File configFile = new File("generatorConfig.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);

    } public static void main(String[] args) throws Exception {try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Generated code:

3.4 Copy the generated mapper file to the directory specified in the project

3.4.1mapper.xml

Copy the Mapper.xml file to mapper Directory

3.4.2mapper.java

Copy the Mapper.xml file to the mapper directory

Note: The mapper.xml file and the mapper.java file are in the same directory and The file names are the same.

3.4.3mapper interface test

  = ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"=(ItemsMapper) applicationContext.getBean("itemsMapper" ="手机" =ItemsExample.Criteria criteria="笔记本3"List<Items> list= =itemsMapper.selectByPrimaryKey(1 Items items=itemsMapper.selectByPrimaryKey(1"水杯"

4. Reverse engineering precautions

4.1Mapper file content is not overwritten but appended

## When the #XXXMapper.xml file already exists, if it is regenerated, the contents of the mapper.xml file will not be overwritten but will be appended, resulting in mybatis parsing failure.

Solution: Delete the originally generated mapper.xml file and generate it again.

The po and mapper.java files automatically generated by MyBatis are not content appended but directly overwritten without this problem.

4.2 Table schema problem

The following is a schema problem for generating code for Oracle database tables:

Schema is the database schema. One user in Oracle corresponds to one schema, which can be understood as The user is the schema. When there are multiple Schemas in the Oracle database that can access the same table name, using mybatis to generate mapper.xml for the table will cause duplication of mapper content, resulting in mybatis parsing errors.

Solution: Fill in the schema in the table as follows:

XXXX is the name of a schema , remove the schema prefix of mapper.xml in batches after generation. If not removed, the query will fail when the Oracle user changes the sql statement.

Quick operation method: Batch replacement in mapper.xml file: "from XXXX." is empty.

The schema of Oracle query object can be queried from dba_objects, as follows:

select * from dba_objects

The above is the detailed content of Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis reverse engineering. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn