Reverse engineering Generation code for "MyBatis Learning 15" MyBatis

Source: Internet
Author: User

1. What is reverse engineering

A major feature of MyBatis is the need for programmers to write their own SQL, then if the table too much, it will inevitably be very troublesome, so MyBatis officially provides a reverse engineering, can be automatically generated for a single table MyBatis execute the required code (including Mapper.xml, Mapper.java, Po. )。 Generally in development, the common reverse engineering method is to generate code from the database table.

2. Using Reverse engineering

Use MyBatis reverse engineering, need to import reverse engineering jar package, I use mybatis-generator-core-1.3.2, has been uploaded to download channel (point I download), the following began to summarize the use of MyBatis reverse engineering steps.

2.1 Create a new project (important)

We're going to create a new Java project, which is designed to generate code using reverse engineering. Some people may ask, why create a new project? Directly in the original project do you want to generate it? This is true, it can be generated in the original project, but it is risky, because MyBatis is generated from the configuration file (said below), if the generated path has the same file, then it will overwrite the original file, so there is a risk. So it's not cumbersome and safe to create a new Java project in development and then copy the resulting files to your project. As follows:

From this, 1 is the Java code to execute, execute it to generate the code we need, 2 is the execution process of the new package, the package can be specified in the 4 configuration file, preferably with our own project package name consistent, can be copied directly later, there is no need to modify the package name; 3 is the jar bag. ; 4 is a configuration file. The following is a detailed analysis.

2.1 Generating the code configuration file

MyBatis Reverse engineering generate code requires a configuration file, the name of the random. The MyBatis will then generate the corresponding code based on the configuration in this configuration file. After downloading the jar package, there is a help document, open after the configuration file template, here will not repeat, the following first write the configuration file:

<?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 automatically 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 ="Jdbc:mysql://localhost:3306/mybatis" userId="root"password= "root">                                </jdbcconnection>        <!--<jdbcconnection driverclass= "Oracle.jdbc.OracleDriver" Connectionurl= "jdbc:oracle:thin:@127.0.0. 1:1521:YYCG "userid=" YYCG "password=" YYCG "> </jdbcConnection> --        <!--default False to parse the JDBC decimal and NUMERIC types to Integer, true to parse the JDBC decimal and NUMERIC types to Java.math.BigDecimal-->< /c3>        <javatyperesolver>            < property name="Forcebigdecimals" value="false" />         </javatyperesolver>        <!--targetproject: the location to generate PO class, Important!! -        <javamodelgenerator targetpackage= "mybatis.po"targetproject=". \ src ">                        <!--enablesubpackages: Do you want the schema to be a suffix of the package--            < 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 generation location, important!! -        <sqlmapgenerator targetpackage="Mybatis.mapper"targetproject =". \src">                         < property name="Enablesubpackages" value="false" />        </sqlmapgenerator>        <!--Targetpackage:mapper interface generated location, important!! -        <javaclientgenerator type= "xmlmapper"targetpackage=" Mybatis.mapper "targetproject=". \src ">                                     < property name="Enablesubpackages" value="false" />        </javaclientgenerator>        <!--Specify the database tables, which tables to generate, which tables to write, to correspond with the database, can not write wrong! -        <table tableName="items"></table>        <table tableName="Orders"></table>        <table tableName="OrderDetail"></table>        <table tableName="user"></table>            </Context></generatorconfiguration>

As you can see from the configuration file above, the main things to do in the configuration file are:

  1. Connect to the database, which is necessary, or how to generate code based on the database table?
  2. Specify the location where you want to generate code, including the Po class, Mapper.xml, and Mapper.java
  3. Specify which tables in the database you want to generate
2.3 Executing the Build program

The configuration file is done, and then you can generate the generated Java program by executing the following build program, which has the following examples in the downloaded reverse engineering document:

 Public  class generatorsqlmap {     Public void Generator()throwsexception{list<string> warnings =NewArraylist<string> ();BooleanOverwrite =true;//pointing to 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 void Main(string[] args)throwsException {Try{Generatorsqlmap Generatorsqlmap =NewGeneratorsqlmap ();        Generatorsqlmap.generator (); }Catch(Exception e)        {E.printstacktrace (); }    }}

Run it, then refresh the project after running, you can see the latest generated code.

Here you can see that there is a detail, each PO class more than one thing, is Xxxexample.java, this class is for the user to customize SQL is used, I will mention later. This will be done here, and we'll copy the generated code to our own project, and for the sake of simplicity, I'll copy itemsmapper.java/itemsmapper.xml/items.java/. Itemsexample.java This category, the others are the same.

3. Test the generated code

We create a new test class for Itemsmapper.java to test several of these methods:

 Public  class itemsmappertest {    PrivateSqlsessionfactory sqlsessionfactory;@Before     Public void setUp()throwsException {//Create SqlsessionfactoryString resource ="Sqlmapconfig.xml";//mybatis configuration file        //Get configuration file streamInputStream InputStream = resources.getresourceasstream (Resource);//Create session factory Sqlsessionfactory, stream the profile to pass in the MybaitsSqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); }//normal insertion, same as our previous insertion    @Test     Public void Testinsert() {sqlsession sqlsession = sqlsessionfactory.opensession ();        Itemsmapper itemsmapper = Sqlsession.getmapper (Itemsmapper.class); Items items =NewItems (); Items.setname ("mobile"); Items.setprice ( thef); Items.setcreatetime (NewDate ());        Itemsmapper.insert (items); Sqlsession.commit ();//There is also a insertselective (items) method, which inserts the field into SQL only if the inserted item is not empty        //Can be automatically generated under the XML file will know. }//Custom query    @Test     Public void Testselectbyexample() {sqlsession sqlsession = sqlsessionfactory.opensession (); Itemsmapper itemsmapper = Sqlsession.getmapper (Itemsmapper.class);//Custom query, this is used in the Itemsexample class, there is a criteria inner class, specifically used to encapsulate the custom query conditionsItemsexample itemsexample =NewItemsexample (); Itemsexample.criteria Criteria = Itemsexample.createcriteria ();//andnameequalto equivalent to stitching a "and name= ' backpack" in SQL        //There are many other methods that are used to customize the query criteria, you can look at the different methodsCriteria.andnameequalto ("Backpack");        list<items> itemslist = itemsmapper.selectbyexample (itemsexample);    System.out.println (itemslist); }//Based on primary key query, same as original    @Test     Public void Testselectbyprimarykey() {Itemsmapper itemsmapper = Sqlsessionfactory.opensession (). Getmapper (Itemsmapper.class); Items items = Itemsmapper.selectbyprimarykey (1);    SYSTEM.OUT.PRINTLN (items); }//update item according to primary key, same as original    @Test     Public void Testupdatebyprimarykey() {sqlsession sqlsession = sqlsessionfactory.opensession ();        Itemsmapper itemsmapper = Sqlsession.getmapper (Itemsmapper.class); Items items = Itemsmapper.selectbyprimarykey (1); Items.setprice (3540f);        Itemsmapper.updatebyprimarykey (items);    Sqlsession.commit (); }}

It can be seen that the reverse engineering generated code, basically the same as before, but it is more normative, but also a lot of custom query conditions Java class, it is very convenient to use. The reverse engineering of the MyBatis is summed up here.
  

Related reading: http://blog.csdn.net/column/details/smybatis.html
Learning Note Source: Https://github.com/eson15/MyBatis_Study

-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15

Reverse engineering Generation code for "MyBatis Learning 15" MyBatis

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.