MyBatis Study Note (v): MyBatis Reverse Engineering

Source: Internet
Author: User
Tags add time deprecated generator one table ssl connection log4j
MyBatis Study Note (v): MyBatis Reverse Engineering

In daily development, if there are more than one table in the database, it is too cumbersome to manually create multiple Pojo classes and write SQL syntax configuration files, MyBatis also provides a one-click operation to generate these files, which we call MyBatis reverse engineering. In general, we use tables from the database to generate Java code in development.

MyBatis Reverse Engineering Download

Post Officer Net Link: Mybatis Generator

Of course, for the download of the jar package, we can use MAVEN import directly:

<dependency>    <groupId>org.mybatis.generator</groupId>    <artifactId>mybatis-generator-core</artifactId>    <version>1.3.7</version></dependency>
Run Reverse engineering

Mybatis Generator offers several ways to run reverse engineering:

Can be run through MAVEN engineering, Java programs, Eclipse plug-ins, etc., for subsequent development compatibility issues, where we use Java programs to be configured in XML, without relying on development tools.

MyBatis Reverse Engineering Example

Here we demonstrate the operation of MyBatis reverse engineering through a concrete example.

    • Create a new MAVEN project: Mybatis-generator. To configure the Pom.xml file, import the associated jar package:
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http: Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Cn.itcast</groupid> <artifactId>mybatis-generator</artifactId> <version>1.0-SNAPSHOT< /version> <dependencies> <!--mysql driver--<dependency> <groupid>my Sql</groupid> <artifactId>mysql-connector-java</artifactId> <version>8.0.12& Lt;/version> </dependency> <!--mybatis Core Jar Pack---<dependency> <g Roupid>org.mybatis</groupid> <artifactId>mybatis</artifactId> <version>3. 4.6</version> </dependency> <!            --mybatis additional feature packs, such as log functions, etc.-<dependency> <groupId>org.apache.ant</groupId>        <artifactId>ant</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactid>ant-launcher&            lt;/artifactid> <version>1.9.6</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <ver sion>5.2</version> </dependency> <dependency> <groupid>cglib</group id> <artifactId>cglib</artifactId> <version>3.2.5</version> </d ependency> <dependency> <groupId>commons-logging</groupId> <artifacti D>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency>            <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.22.0-GA</version> </dependency> <dependency> <groupid>lo         G4j</groupid> <artifactId>log4j</artifactId> <version>1.2.17</version>            </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.3</version> </depende ncy> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifa Ctid>log4j-core</artifactid> <version>2.3</version> </dependency> <          Dependency>  <groupId>ognl</groupId> <artifactId>ognl</artifactId> <version>3.1.1             6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </de pendency> <dependency> <groupId>org.slf4j</groupId> &LT;ARTIFACTID&GT;SL         F4j-log4j12</artifactid> <version>1.7.25</version> <scope>test</scope> </dependency> <!--mybatis-generator--<dependency> <groupid>or G.mybatis.generator</groupid> <artifactId>mybatis-generator-core</artifactId> < Version>1.3.7</version> </dependency> </dependencies></project>
    • Create a build code profile under Resources 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> <context id=" Testtables "            Targetruntime= "MyBatis3" > <commentGenerator> <!--whether to remove auto-generated comments true: Yes: false: no-- <property name= "Suppressallcomments" value= "true"/> </commentGenerator> <!--database connection information: Driver class, connection address, user name, password--<jdbcconnection driverclass= "Com.mysql.jdbc.Driver" Connectionurl= "J Dbc:mysql:///sampledb "userid=" root "password=" "> </jdbcconnect Ion> <!--default false, the JDBC decimal and NUMERIC types are parsed to Integer, and the JDBC decimal and NUMERIC types are resolved to JAVA.M when True Ath. BigDecimal-<javaTypeResolver> <property name= "Forcebigdecimals" vaLue= "false"/> </javaTypeResolver> <!--targetproject: The location of the PO class is generated--<javamodelgenera Tor targetpackage= "Cn.itcast.ssm.po" targetproject= "Src/main/java" > <!--enabl Esubpackages: Do you want the schema as the package suffix--<property name= "Enablesubpackages" value= "false"/> <!-         -The value returned from the database is cleared before and after the space-<property name= "Trimstrings" value= "true"/> </javaModelGenerator>                         <!--targetproject:mapper Map file generated location-<sqlmapgenerator targetpackage= "Cn.itcast.ssm.mapper"            targetproject= "Src/main/java" > <!--enablesubpackages: Do you want the schema to be a suffix of the package-- <property name= "Enablesubpackages" value= "false"/> </sqlMapGenerator> <!--targetpackage:m Apper interface generated Location--<javaclientgenerator type= "Xmlmapper" targetpackage= "Cn.itcast.s              Sm.mapper "               targetproject= "Src/main/java" > <!--enablesubpackages: Do you want the schema to be the suffix of the package--and &L        T;property name= "Enablesubpackages" value= "false"/> </javaClientGenerator> <!--Specify database table--  <table tablename= "Items" ></table> <table tablename= "Orders" ></table> <table Tablename= "OrderDetail" ></table> <table tablename= "user" ></table> <!--some table fields need to specify JA VA type <table schema= "" Tablename= "" > <columnoverride column= "" javatype= ""/> </ta Ble>-</context></generatorConfiguration>

We specify the required file path:

javaModelGenerator: The location of the PO class is generated.

sqlMapGenerator: Mapper the location where the map file was generated.

javaClientGenerator: The location generated by the Mapper interface.

table: Specifies the database table.

Important:

It is important to note here that the MySQL database configuration, if you press the above configuration file, will report the following error:

Loading class com.mysql.jdbc.Drive . This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver . The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

In fact, because we imported the Mysql-connector package using a new driver, the above is com.mysql.jdbc.Driver deprecated, we recommend that we use com.mysql.cj.jdbc.Driver , and should also be in the URL of the connection need to add time zone information. In addition, we also need to set Usessl=false to explicitly disable SSL connection, otherwise it will also be reported on the SSL connection error.

Read as follows:

<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"                        connectionURL="jdbc:mysql:///sampledb?serverTimezone=GMT&amp;useSSL=false"                        userId="root"                        password=""></jdbcConnection>
    • Create a generator Generatorsqlmap.java, execute the generator, generate MyBatis reverse engineering:
Package Cn.itcast.ssm.generator;import Org.mybatis.generator.api.mybatisgenerator;import Org.mybatis.generator.config.configuration;import Org.mybatis.generator.config.xml.configurationparser;import Org.mybatis.generator.internal.defaultshellcallback;import Java.io.file;import Java.util.ArrayList;import Java.util.list;public class Generatorsqlmap {public void Generator () throws Exception {list<string> warn        ings = new arraylist<string> ();        Boolean overwrite = true; Specifies the reverse engineering profile, File ConfigFile = new file ("/users/weixuqin/ideaprojects/mybatis-generator/src/main/resources/generato        Rconfig.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 (); }    }}
    • Post-build directory:

Note:

Here I met a problem, I have to write a log file, but do not know why always can not load the log information, reported the following information, access to the relevant information has not been able to solve the problem, there will be time for themselves to solve the problem.

Apply MyBatis Reverse engineering files

We can copy and paste items from reverse engineering to our own other projects, and it is not recommended to use MyBatis generator generation in legacy projects because of the problem of naming conflict overrides.

Here we will Itemsmapper.java, Itemsmapper.xml, Items.java, Itemsexample.java copy paste into our original project, write test file Itemsmappertest.java, To query the records for "notebooks" in the database:

Package Cn.itcast.ssm.test;import Cn.itcast.ssm.mapper.itemsmapper;import Cn.itcast.ssm.po.items;import Cn.itcast.ssm.po.itemsexample;import Org.junit.before;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Java.util.list;public Class    itemsmappertest {private ApplicationContext applicationcontext;    Private Itemsmapper Itemsmapper; In Setup this method gets the spring container @Before public void SetUp () throws exception{ApplicationContext = new Classpathxml        ApplicationContext ("Classpath:config/spring/applicationcontext.xml");    Itemsmapper = (itemsmapper) applicationcontext.getbean ("Itemsmapper");        } @Test public void Testselectbyexample () {itemsexample itemsexample = new Itemsexample ();        Construct query criteria through criteria Itemsexample.criteria criteria = Itemsexample.createcriteria ();        Criteria.andnameequalto ("Notebook"); More than one record may be returned List<items> list = Itemsmapper.selectbyexample (itemsexample);    SYSTEM.OUT.PRINTLN (list); }}

The output results are as follows:

Here I just started to run the time can not find Selectbyexample () This method, in fact, because I can not find my mapper.xml mapping file, puzzled for a long, found that Mapper.xml did not publish to the target file, (idea, eclipse Without this problem, the interface class and the mapping file are allowed in the same directory.

So we should put the mapping file in the Resourcs directory, and then load the mapping file in the MyBatis global configuration file, execute the test file again, and we will not find our mapping file.

<!-- 加载映射文件 -->    <mappers>        <!-- 通过 resource 方法一次加载一个映射文件 -->        <mapper resource="config/sqlmap/ItemsMapper.xml"/>    </mappers>

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.