Spring+springmvc+mybatis Deep Learning and building (10)--mybatis Reverse engineering

Source: Internet
Author: User

Reprint Please specify source: http://www.cnblogs.com/Joanna-Yan/p/6973266.html

Mentioned earlier: Spring+springmvc+mybatis in-depth study and build (ix)--mybatis and Spring integration

Use the Mapper Auto-generate tool mybatis-generator-core-1.3.2 on the official website to generate PO classes and mapper mapping files.

1. What is reverse engineering

MyBatis requires programmers to write their own SQL statements, MyBatis officially provide reverse engineering can be automatically generated for a single table MyBatis execute the required code (Mapper.java, Mapper.xml, po ... )

In the actual development of enterprises, the commonly used reverse engineering methods:

The Java code is generated by the tables in the database.

2. Download Reverse Engineering

3. How to use (requirements will be used)

In order to prevent late database table modification, extension, requirements modification and other reasons, the update auto-generated Po,mapper overwrite error. We create a new, reverse-generated project Generatorsqlmapcustom, and then copy the automatically generated po,mapper to the project as required.

3.1 Running Reverse engineering

It is recommended that you use Java programming methods without relying on development tools.

3.2mapper Build configuration file

To configure the details of the mapper build in Gengeratorconfig.xml, note the following:

(1) Add the database tables to be generated;

(2) PO file package path;

(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>    <ContextID= "Testtables"Targetruntime= "MyBatis3">        <Commentgenerator>            <!--whether to remove automatically generated comments true: Yes: false: No -            < Propertyname= "Suppressallcomments"value= "true" />        </Commentgenerator>        <!--Database connection Information: Driver class, connection address, user name, password -        <jdbcconnectionDriverclass= "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> -        <!--by default, the JDBC decimal and NUMERIC types are parsed to Integer, and the JDBC decimal and NUMERIC types are resolved to Java.math.BigDecimal when True. /c10> -        <Javatyperesolver>            < Propertyname= "Forcebigdecimals"value= "false" />        </Javatyperesolver>        <!--Targetproject: Where to generate the PO class -        <JavamodelgeneratorTargetpackage= "Joanna.yan.po"Targetproject= ". \src">            <!--enablesubpackages: Do you want the schema to be the suffix of the package -            < Propertyname= "Enablesubpackages"value= "false" />            <!--The space returned from the database before and after the value is cleaned -            < Propertyname= "Trimstrings"value= "true" />        </Javamodelgenerator>        <!--Targetproject:mapper The location of the map file generation -        <SqlmapgeneratorTargetpackage= "Joanna.yan.mapper"Targetproject= ". \src">            <!--enablesubpackages: Do you want the schema to be the suffix of the package -            < Propertyname= "Enablesubpackages"value= "false" />        </Sqlmapgenerator>        <!--Targetpackage:mapper the location generated by the interface -        <Javaclientgeneratortype= "Xmlmapper"Targetpackage= "Joanna.yan.mapper"Targetproject= ". \src">            <!--enablesubpackages: Do you want the schema to be the suffix of the package -            <PRoperty name= "Enablesubpackages"value= "false" />        </Javaclientgenerator>        <!--Specify database Tables -        <TableTableName= "Items"></Table>        <TableTableName= "Orders"></Table>        <TableTableName= "OrderDetail"></Table>        <TableTableName= "User"></Table>        <!--<table schema= "" Tablename= "Sys_user" ></table> <table schema= "" Tablename= "Sys_role" ></t able> <table schema= "" Tablename= "Sys_permission" ></table> <table schema= "" Tablename= "sys _user_role "></table> <table schema=" "Tablename=" Sys_role_permission "></table> -                <!--some table fields need to specify the Java type <table schema= "" Tablename= "" > <columnoverride column= "" Javatype= "/&G        T </table> -    </Context></generatorconfiguration>
3.3 Using Java classes to generate mapper files
 Public classGeneratorsqlmap { Public voidGenerator ()throwsexception{List<String> warnings =NewArraylist<string>(); BooleanOverwrite =true; //Specifying a reverse engineering configuration fileFile ConfigFile =NewFile ("Generatorconfig.xml"); Configurationparser CP=Newconfigurationparser (warnings); Configuration Config=cp.parseconfiguration (configfile); Defaultshellcallback Callback=Newdefaultshellcallback (overwrite); Mybatisgenerator Mybatisgenerator=Newmybatisgenerator (config, callback, warnings); Mybatisgenerator.generate (NULL); }      Public Static voidMain (string[] args)throwsException {Try{generatorsqlmap Generatorsqlmap=NewGeneratorsqlmap ();        Generatorsqlmap.generator (); } Catch(Exception e) {e.printstacktrace (); }    }}

Post-generated code:

3.4 Copy the generated mapper file into the directory specified in the project 3.4.1mapper.xml

Copy the Mapper.xml file to the 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 within a directory and have the same file name.

3.4.3mapper Interface Test
 Public classItemsmappertest {PrivateApplicationContext ApplicationContext; PrivateItemsmapper Itemsmapper; @Before Public voidsetUp () {ApplicationContext=NewClasspathxmlapplicationcontext ("Classpath:spring/applicationcontext.xml"); Itemsmapper= (itemsmapper) applicationcontext.getbean ("Itemsmapper"); } @Test Public voidTestinsert () {Items Item=NewItems (); Item.setname (Phone); Item.setprice (999f);
Item.setcreatetime (New Date ()); Itemsmapper.insert (item); } //Custom Condition Query@Test Public voidtestselectbyexample () {itemsexample itemsexample=Newitemsexample (); //construct query criteria by criteriaItemsexample.criteria criteria=Itemsexample.createcriteria (); Criteria.andnameequalto ("Notebook 3"); //more than one record may be returnedList<items> list=itemsmapper.selectbyexample (itemsexample); SYSTEM.OUT.PRINTLN (list); } //query based on primary key@Test Public voidTestselectbyprimarykey () {Items Items=itemsmapper.selectbyprimarykey (1); SYSTEM.OUT.PRINTLN (items); } @Test Public voidTestupdatebyprimarykey () {//To update all fields, you need to query them and update them first.Items Items=itemsmapper.selectbyprimarykey (1); Items.setname ("Water Cup"); Itemsmapper.updatebyprimarykey (items); //If the incoming field is not empty to update, use this method in a bulk update, no need to query and update firstitemsmapper.updatebyprimarykeyselective (items); }}
4. Reverse engineering Precautions 4.1Mapper file content is not overwritten but appended

If the Xxxmapper.xml file already exists, the Mapper.xml file content is not overwritten but the content is appended, resulting in MyBatis parsing failure.

WORKAROUND: Delete the previously generated mapper.xml file and build again.

MyBatis automatically generated PO and Mapper.java files are not appended to the content but are directly overwritten without this problem.

4.2 Table Schema problem

Below is the schema issue for generating code for Oracle database tables:

Schema is the database schema, one user in Oracle corresponds to a schema, which can be understood as the schema of the user. When there are multiple schemas in the Oracle database that can access the same table name, mapper.xml that uses MyBatis to generate the table will have mapper content duplication, resulting in mybatis parsing errors.

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

<table schema= "XXXX" Tablename= "" >

XXXX is the name of a schema, generated after the Mapper.xml schema prefix batch removed, if not removed, when the Oracle user changed the SQL statement will fail the query.

Quick action: Batch replacement in Mapper.xml file: "From XXXX." is empty.

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

SELECT * FROM Dba_objects

If this article is helpful to you, please give me a reward!

Spring+springmvc+mybatis Deep Learning and building (10)--mybatis Reverse engineering

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.