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> <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/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> - <!--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 - <Javatyperesolver> < Propertyname= "Forcebigdecimals"value= "false" /> </Javatyperesolver> <!--targetproject: Generate PO class location, Important!! - <JavamodelgeneratorTargetpackage= "Mybatis.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 Map File generation location, important!! - <SqlmapgeneratorTargetpackage= "Mybatis.mapper"Targetproject= ". \src"> < Propertyname= "Enablesubpackages"value= "false" /> </Sqlmapgenerator> <!--Targetpackage:mapper Interface generated location, important!! - <Javaclientgeneratortype= "Xmlmapper"Targetpackage= "Mybatis.mapper"Targetproject= ". \src"> < Propertyname= "Enablesubpackages"value= "false" /> </Javaclientgenerator> <!--Specify database tables, which tables to generate, which tables to write, and the database to correspond to, can not write wrong! - <TableTableName= "Items"></Table> <TableTableName= "Orders"></Table> <TableTableName= "OrderDetail"></Table> <TableTableName= "User"></Table> </Context></generatorconfiguration>
As you can see from the configuration file above, the main things to do in the configuration file are:
- Connect to the database, which is necessary, or how to generate code based on the database table?
- Specify the location where you want to generate code, including the Po class, Mapper.xml, and Mapper.java
- 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 classGeneratorsqlmap { Public voidGenerator ()throwsexception{List<String> warnings =NewArraylist<string>(); BooleanOverwrite =true; //point 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 voidMain (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 classItemsmappertest {Privatesqlsessionfactory sqlsessionfactory; @Before Public voidSetUp ()throwsException {//Create SqlsessionfactoryString resource = "Sqlmapconfig.xml";//mybatis configuration file//get the flow of the configuration fileInputStream InputStream =Resources.getresourceasstream (Resource); //create a stream of Session factory Sqlsessionfactory, to pass in the Mybaits configuration fileSqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); } //normal insertion, just like the one we inserted before.@Test Public voidTestinsert () {sqlsession sqlsession=sqlsessionfactory.opensession (); Itemsmapper Itemsmapper= Sqlsession.getmapper (itemsmapper.class); Items Items=NewItems (); Items.setname (Phone); Items.setprice (5000F); Items.setcreatetime (NewDate ()); Itemsmapper.insert (items); Sqlsession.commit (); //There is also a insertselective (items) method, in which the inserted item is not empty before stitching the field into SQL//you can see the XML files that are generated automatically. } //Custom Queries@Test Public voidtestselectbyexample () {sqlsession sqlsession=sqlsessionfactory.opensession (); Itemsmapper Itemsmapper= Sqlsession.getmapper (itemsmapper.class); //custom query, which is used in the Itemsexample class, there is a criteria inner class, specifically used to encapsulate the custom query criteriaItemsexample itemsexample =Newitemsexample (); Itemsexample.criteria Criteria=Itemsexample.createcriteria (); //Andnameequalto equivalent to stitching a "and name= ' backpack" in SQL//There are many other ways to customize the query criteria, you can look at the different methodsCriteria.andnameequalto ("Backpack"); List<Items> itemslist =itemsmapper.selectbyexample (itemsexample); System.out.println (itemslist); } //according to the primary key query, the same as the original@Test Public voidTestselectbyprimarykey () {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 voidTestupdatebyprimarykey () {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.
Reverse engineering Generation code for "MyBatis Learning 15" MyBatis