1. What is reverse engineering
One of the main features of MyBatis is the need for programmers to write their own SQL, so if the table is too much, it will be difficult, so MyBatis official provides a reverse engineering, can automatically generate MyBatis for a single table to execute the required code (including Mapper.xml, Mapper.java, Po ... )。 Generally in the development, the commonly used reverse engineering way is to generate the code through the database table. 2. Using Reverse engineering
Use MyBatis reverse engineering, need to import the reverse engineering jar package, I used the mybatis-generator-core-1.3.2, has been uploaded to the download channel (point I download), the following start to summarize the MyBatis reverse engineering use steps. 2.1 Create a new project (important)
We're going to create a new Java project that is designed to generate code using reverse engineering. Some people may ask why a new project should be built. Directly in the original project you want to generate is not OK. This is true, it can be generated in the original project, but there is a risk, because the MyBatis is generated from the configuration file (as the following), if the generated path has the same file, it will overwrite the original file, there is a risk. So it's not cumbersome and safe to create a new Java project in development and then copy the generated files to your project. As follows:
From the figure above, 1 is the Java code to execute, which can be executed to generate the code we need; 2 is the implementation of the new package, this package can be specified in 4 of the configuration file, preferably with our own project package name consistent, the following can be directly copied, you do not need to modify the package name; 3 is the jar bag. ; 4 is the configuration file. The following is a detailed analysis. 2.1 configuration file to generate code
MyBatis The reverse engineering generation code requires a configuration file, and the name is random. MyBatis then generates the appropriate code based on the configuration in the configuration file. After downloading the jar package, which has the help document, opens inside has the configuration file template, here will not repeat, the following first writes the configuration file:
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en G/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id=" Testtables "
Targetruntime= "MyBatis3" > <commentGenerator> <!--whether to remove automatically generated comments true: false: No--> <property name= "Suppressallcomments" value= "true"/> </commentGenerator> <!--database connection Info: Driver class, connection address, username, password--> <jdbcconnection driverclass= "Com.mysql.jdbc.Driver connectionurl=" jdbc:m Ysql://localhost:3306/mybatis "userid=" root "password=" root "> </jdbcConnection> <! --<jdbcconnection driverclass= "Oracle.jdbc.OracleDriver" connectionurl= "jdbc:oracle:thin:@127.0.0.1:1521:y
YCG "userid=" YYCG "password=" YYCG "> </jdbcConnection>--> <!--default false to resolve JDBC decimal and NUMERIC types to Integer, and to True to resolve JDBC decimal and NUMERIC types to Java.math.BigDecimal--> <javaTypeResolver> <property name= "Forcebigdecimals" value= "false"/> </javatypereso Lver> <!--targetproject: Position of PO class, important. --> <javamodelgenerator targetpackage= "Mybatis.po" targetproject= "\src" > <!--
Enablesubpackages: Let schema be the suffix of the package--> <property name= "Enablesubpackages" value= "false"/> <!--the space--> <property name= "trimstrings" value= "true"/> before and after the value returned from the database is cleaned </javamodelgen erator> <!--targetproject:mapper mapping file generation location, important. --> <sqlmapgenerator targetpackage= "Mybatis.mapper" targetproject= ". \src" > <p Roperty name= "Enablesubpackages" value= "false"/> </sqlMapGenerator> <!--targetpackage:mapper The location where the interface is generated is important. --> <javaclientgenerator type= "Xmlmapper" targetpackage= "Mybatis.mapper" targetproject= ". \src" > <property name= "Enablesubpackages" value= "false"/> </javaClientGenerator> <!-- Specify the database table, which tables to generate, what tables to write, and the database to be 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 thing to do in a configuration file is to connect to a database, which is necessary, or how to generate code from a database table. Specify where you want to generate the code, including the Po class, Mapper.xml and Mapper.java specify which table 2.3 to build in the database to execute the build program
The configuration file is well done, and then the following generators can be generated, generated Java programs, downloaded in reverse engineering documents are examples, as follows:
public class Generatorsqlmap {public void Generator () throws exception{List<st
ring> warnings = new arraylist<string> ();
Boolean overwrite = true;
Point to Reverse engineering profile 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 (); }
}
}
Run it, and then refresh the project after the run, you can see the latest generated code.
Here's a little bit of detail, one more thing for each PO class, which is Xxxexample.java, which is used to customize SQL for the user, which I'll mention later. Here it is generated, we will copy the generated code to their own project use, for simplicity, here I copy itemsmapper.java/itemsmapper.xml/items.java/ Itemsexample.java This category, the other is the same. 3. Test the generated code
We create a new test class for Itemsmapper.java and test several of these methods:
public class Itemsmappertest {private Sqlsessionfactory sqlsessionfactory; @Before public void SetUp () throws Exception {//create sqlsessionfactory String resource = "Sqlmapconfig. XML ";
MyBatis profile//Get configuration file stream InputStream InputStream = resources.getresourceasstream (Resource); Create a session factory Sqlsessionfactory, to pass in the mybaits configuration file stream sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream)
; //Normal insert, same as our previous insert @Test public void Testinsert () {sqlsession sqlsession = Sqlsessionfactory.ope
Nsession ();
Itemsmapper itemsmapper = Sqlsession.getmapper (Itemsmapper.class);
Items items = new items ();
Items.setname ("mobile");
Items.setprice (5000F);
Items.setcreatetime (New Date ());
Itemsmapper.insert (items);
Sqlsession.commit ();
There is also a insertselective (items) method, when the inserted item is not empty, the field is spliced into SQL//can be automatically generated by the XML file. }//Custom query @Test public void Testselectbyexample () {sqlsession sqlsession = sqlsessionfactory.opensession ();
Itemsmapper itemsmapper = Sqlsession.getmapper (Itemsmapper.class);
Custom query, which uses the Itemsexample class, which has a criteria inner class, which is designed to encapsulate the itemsexample itemsexample of custom query conditions = new Itemsexample ();
Itemsexample.criteria Criteria = Itemsexample.createcriteria (); Andnameequalto is equivalent to stitching an "and name= ' backpack" in SQL "//There are many other ways to customize the query criteria, and you can look at the different ways Criteria.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 void Testselectbyprimarykey () {Itemsmapper itemsmapper = Sqlsessionfac
Tory.opensession (). Getmapper (Itemsmapper.class);
Items items = Itemsmapper.selectbyprimarykey (1);
SYSTEM.OUT.PRINTLN (items); ///update item according to primary key @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 more custom query conditions Java class, it is very convenient to use. The reverse engineering of MyBatis is summed up here.
Related reading: http://blog.csdn.net/column/details/smybatis.html
Learn notes Source download address: Https://github.com/eson15/MyBatis_Study
-– is willing to share and make progress together.
-– my Blog Home: http://blog.csdn.net/eson_15