Mybatis Code generation Tool

Source: Internet
Author: User

The Mybatis application, which requires a large number of configuration files, is completely hand-configured for hundreds of thousands of database tables, which is a horrible workload. So Mybatis official also launched a jar package for the Mybatis code generation tool.

first download the Mybatis-generator-core-1.3.2-bundle.zip file, then unzip it with two folders

Docs is a directory of Help documents; The Lib directory is a jar package that needs to be mybatis-generator-core-1.3.2.jar and copied to the Java project we just created;

Follow the Doc documentation reference for Mybatis generator, such as:e:/jar/mybatis-generator-core-1.3.2/docs/configreference/xmlconfig.html

Initial configuration out of a ready-to-use version, I put the source code also provides download, Mybatis code generation tool, the main features:

    1. Generate Pojo corresponds to database structure
    2. If you have a primary key, you can match the primary key
    3. If there is no primary key, you can use the other fields to match
    4. Dynamic Select,update,delete method
    5. Automatically generate interfaces (that is, the previous DAO layer)
    6. Automatically generate SQL Mapper, delete and modify various statement configurations, including dynamic where statement configuration
    7. Generate Example examples for reference
Specific steps:Configure the configuration file for the Mybatis code generation toolbefore using the Mybatis code generation tool, these directories must be created, and as a good application, these directories are created in a regular pattern.

(1) in the created Web project, create the appropriate package such as:

(2)Com.hlx.inter is used to store Mybatis interface objects.

(3)Com.hlx.mapper is used to store SQL mapper corresponding mappings, SQL statements, etc.

(4)Com.hlx.model is used to store the model corresponding to the database.

(5) com.hlx.test for testing.

(a) According to the Mybatis Code generation tool documentation, a configuration file is required, which is named: generatorConfiguration.xml placed in the SRC directory.

<?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> <!--Configure the path of the Oracle drive jar package; Here is the absolute path--<classpathentry location= "E:\jar\ojdbc6.jar"/> <!--content configuration--<context id= "Hlx_orac      Le_tables "targetruntime=" MyBatis3 "> <!--to prevent a lot of comments in the generated code, which is ugly, add the following configuration control---<commentGenerator> <property name= "Suppressallcomments" value= "true"/> <property name= "Suppressdate" value= "true"/> &lt ;/commentgenerator> <!--note Control complete-<!--database connection-<jdbcconnection driverclass= "Oracle.jdbc.dri Ver.    Oracledriver "Connectionurl=" Jdbc:oracle:thin: @localhost: 1521:HLX "userid=" Rent "password=" AAA "> </jdbcConnection> <javatyperesolver > <property name= "forcebigdecimals" value= "false"/> </javaTypeResolver> <!--datasheet for model layer--<javamodelgenerator targetpackage= "Com.hlx.model" Targetp roject= "src" > <property name= "enablesubpackages" value= "true"/> <property name= "Trimstrings" value= "True"/> </javaModelGenerator> <!--SQL Mapper insinuate configuration file--<sqlmapgenerator targetpackage= "com. Hlx.mapper "targetproject=" src "> <property name=" enablesubpackages "value=" true "/> </sqlmapgenerator > <!--is the DAO layer in Ibatis2, but in Mybatis3, it's actually mapper interface--<javaclientgenerator type= "Xmlmapper" targetpackage= "Com.hlx.inter" targetproject= "src" > <property name= "enablesubpackages" value= "true"/> </javaclientg Enerator> <!--to generate operations on those datasheets, you must have a table schema= "Rent" tablename= "userinfos" database table Domainobjectname= "Useri NFO "corresponding entity class--<table schema=" Rent "tablename=" Userinfos "domainobjectname=" Userinfo "> </table&  Gt </context&gT </generatorConfiguration>

(b) test the ability to use Mybatis to generate content such as Model,sql mapper corresponding to the Userinfos table just created.

Package Com.hlx.test;import Java.io.file;import Java.io.ioexception;import java.sql.sqlexception;import Java.util.arraylist;import Java.util.list;import Org.junit.test;import Org.mybatis.generator.api.MyBatisGenerator ; Import Org.mybatis.generator.config.configuration;import Org.mybatis.generator.config.xml.ConfigurationParser; Import Org.mybatis.generator.exception.invalidconfigurationexception;import Org.mybatis.generator.exception.xmlparserexception;import Org.mybatis.generator.internal.DefaultShellCallback; public class Generatortest {@Testpublic void Test () {list<string> warnings = new Arraylist<string> (); Boolean Overwrite = true; String gencfg = "/generatorconfiguration.xml"; File ConfigFile = new file (GeneratorTest.class.getResource (gencfg). GetFile ()); Configurationparser cp = new Configurationparser (warnings); Configuration config = null;try {config = cp.parseconfiguration (configfile);} catch (IOException e) {e.printstacktrace () ;} catch (Xmlparserexception e) {E.printstackTrace ();} Defaultshellcallback callback = new Defaultshellcallback (overwrite); Mybatisgenerator Mybatisgenerator = null;try {mybatisgenerator = new Mybatisgenerator (config, callback, warnings);} catch (Invalidconfigurationexception e) {e.printstacktrace ();} try {mybatisgenerator.generate (null);} catch (SQLException e) {e.printstacktrace ()} catch (IOException e) { E.printstacktrace ();} catch (Interruptedexception e) {e.printstacktrace ();}}}
After execution, Remember to refresh the project, which is shown:



Note: in addition to generate SQL Mapper, and so on, just to the single table of additions and deletions, if you have a multi-table join operation, you can manually configure, if you call the stored procedure, you also need to manually configure. This is a lot less work.

If you want to use the command line to handle, it is also possible.

Like what:

java -jar mybatis-generator-core-1.3.2.jar -generatorConfiguration.xm -overwrite

In this case, the absolute path is the only line. Additionally, the configuration of Targetproject in the Generatorconfiguration.xml configuration file must also be an absolute path

To test the code you just generated:

Mybatis.xml configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--Introducing jdbc.properties file--><properties resource= "jdbc.properties"/> <!--(a) Us Erinfos entity class corresponds to an alias _user-<!--This achieves the purpose of simplifying the entity class reference. --><!--<typealiases><typealias type= "Com.hlx.pojo.Userinfos" alias= "_user"/></typealiases >--><!--(b) In addition to setting aliases for an entity class in this way, we can also use the following method to set up aliases for all entity classes under a package as follows:--<!-- To configure aliases for all entity classes under the Com.hlx.pojo package, mybatis The default setting alias is to remove the simple class name of the package where the class is located, such as Com.hlx.pojo.Userinfos, the alias of the entity class will be set to Userinfos--&G t;<typealiases> <package name= "com.hlx.model.rent"/></typealiases><!--Development: Development mode work : Operating mode--><environments default= "development" ><environment id= "development" ><!--configuration Transaction Management, Transaction management with JDBC--><transactionmanager type= "jdbc"/><!--configuration database connection Information Value property value Reference jdbc.propertiesThe values configured in the configuration file--><!--pooled:mybatis data source, JNDI: Tomcat-based data source--><datasource type= "pooled" ><property Name= "Driver" value= "${driver}"/><property name= "url" value= "${url}"/><property name= "username" value= " ${username} "/><property name=" password "value=" ${password} "/></datasource></environment> </environments><!--Add mapper files to the configuration file--><mappers><mapper resource= "com/hlx/mapper/rent/ Userinfomapper.xml "/></mappers></configuration>
Test class:

Package Com.hlx.test;import Java.util.list;import Org.apache.ibatis.session.sqlsession;import org.junit.Test; Import Com.hlx.inter.rent.userinfomapper;import Com.hlx.model.rent.userinfo;import com.hlx.util.MyBatisUtil; public class Testuserinfo {@Testpublic void list () {//get session sqlsession Sessions = Mybatisutil.getsqlsession (true); try {//s HIFT+ALT+Z hint block//interface Userinfomapper Umapper = Session.getmapper (Userinfomapper.class);//Call method list<userinfo> list = Umapper.selectbyexample (null); for (Userinfo userinfo:list) {System.out.println (Userinfo);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {//close session session.close ();}} @Testpublic void Add () {//get session sqlsession Sessions = Mybatisutil.getsqlsession (true); try {//interface userinfomapper umapper = ses Sion.getmapper (Userinfomapper.class);//Call method int count = Umapper.insert (new Userinfo (Ten, "Girl", "198033"));} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {//close session Session.close();}}} 
Effect:





Mybatis Code generation Tool

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.