MyBatis Real-Life tutorials (MyBatis in action) IX: Use of MyBatis code generation tools

Source: Internet
Author: User

MyBatis applications, which require a large number of configuration files, are completely hand-configured for hundreds of thousands of database tables, which is a horrible workload. So MyBatis has also launched a jar package for the MyBatis code generation tool. It took a little time today to follow MyBatis Generator Doc Document reference, the initial configuration of a version that can be used, I put the source code also provides download, MyBatis code generation tool, mainly has the function:
1. Generate Pojo corresponding 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

The following detailed procedures are described below

1. Create a test project and configure the MyBatis code generation jar Package
:Http://code.google.com/p/mybatis/downloads/list?can=3&q=product%3dgenerator
mysql driver download:http://dev.mysql.com/downloads/connector/j/
These jar packages, I will also be included in the source code, can be at the end of the article, download the source code, reference.

build a Dynamic Web project with Eclipse.
unzip the downloaded Mybatis-generator-core-1.3.2-bundle.zip file, which has two directories: A directory is the document directory docs, mainly describes how this code generation tool is used, and the other is the Lib directory,  The content is mainly jar package, here we need Mybatis-generator-core-1.3.2.jar, this jar package. Copy it to the webcontent/web-inf/lib of the WEB project we just created directory. The MySQL driver jar package is also placed in this directory. Because it was tested with MySQL.

2. Create a test table in the database
Create a category table for testing in the MyBatis database (if you do not have mybatis this database to create, this is based on the previous series of articles written, already has mybatis this database)

Drop TABLE IF EXISTS' category ';Create TABLE' category ' (' ID ' )int( One) not NULLauto_increment, ' catname 'varchar( -) not NULL, ' catdescription 'varchar( $)DEFAULT NULL,  PRIMARY KEY(' id ')) ENGINE=InnoDBDEFAULTCHARSET=UTF8;

3. Configure the configuration file for the MyBatis code generation tool
In the Web project that you created, create the appropriate package such as:
The com.yihaomen.inter is used to store MyBatis interface objects.
Com.yihaomen.mapper is used to store SQL mapper corresponding mappings, SQL statements, and so on.
The Com.yihaomen.model is used to store the model corresponding to the database.
Before using the MyBatis code generation tool, these directories must be created, and as a good application, these directories are created in a regular pattern.

According to the MyBatis Code generation tool documentation, a configuration file is required, which is named: Mbgconfiguration.xml is placed in the SRC directory. The contents of the configuration file are as follows:

<?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 MySQL driver jar path. Use absolute path -  <Classpathentry Location= "D:\Work\Java\eclipse\workspace\myBatisGenerator\WebContent\WEB-INF\lib\ Mysql-connector-java-5.1.22-bin.jar " />  <ContextID= "Yihaomen_mysql_tables"Targetruntime= "MyBatis3">      <!--to prevent a lot of comments in the generated code, it is more unsightly to add the following configuration control -    <Commentgenerator>      < Propertyname= "Suppressallcomments"value= "true" />      < Propertyname= "Suppressdate"value= "true" />    </Commentgenerator>    <!--Note Control Complete -      <!--Database Connection -    <jdbcconnectionDriverclass= "Com.mysql.jdbc.Driver"Connectionurl= "Jdbc:mysql://127.0.0.1:3306/mybatis?characterencoding=utf8"userId= "root"Password= "Password">    </jdbcconnection>    <Javatyperesolver>      < Propertyname= "Forcebigdecimals"value= "false" />    </Javatyperesolver>        <!--the model layer corresponding to the data table -    <JavamodelgeneratorTargetpackage= "Com.yihaomen.model"Targetproject= "src">      < Propertyname= "Enablesubpackages"value= "true" />      < Propertyname= "Trimstrings"value= "true" />    </Javamodelgenerator>        <!--SQL Mapper insinuate configuration file -    <SqlmapgeneratorTargetpackage= "Com.yihaomen.mapper"Targetproject= "src">      < Propertyname= "Enablesubpackages"value= "true" />    </Sqlmapgenerator>        <!--In ibatis2 is the DAO layer, but in mybatis3, it is actually the Mapper interface -    <Javaclientgeneratortype= "Xmlmapper"Targetpackage= "Com.yihaomen.inter"Targetproject= "src">      < Propertyname= "Enablesubpackages"value= "true" />    </Javaclientgenerator>        <!--To build on those datasheets, you must have one. -    <TableSchema= "MyBatis"TableName= "category"Domainobjectname= "Category"Enablecountbyexample= "false"Enableupdatebyexample= "false"Enabledeletebyexample= "false"Enableselectbyexample= "false"Selectbyexamplequeryid= "false">         </Table>  </Context></generatorconfiguration>


Use a Main method to test if you can use MyBatis to generate content such as Model,sql Mapper, which corresponds to the ' category ' table you just created.
Create a Com.yihaomen.test package and build a test class Genmain under this package:

 Packagecom.yihaomen.test;ImportJava.io.File;Importjava.io.IOException;Importjava.sql.SQLException;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.mybatis.generator.api.MyBatisGenerator;Importorg.mybatis.generator.config.Configuration;ImportOrg.mybatis.generator.config.xml.ConfigurationParser;Importorg.mybatis.generator.exception.InvalidConfigurationException;Importorg.mybatis.generator.exception.XMLParserException;ImportOrg.mybatis.generator.internal.DefaultShellCallback; Public classGenmain { Public Static voidMain (string[] args) {List<String> warnings =NewArraylist<string>(); BooleanOverwrite =true; String gencfg= "/mbgconfiguration.xml"; File ConfigFile=NewFile (Genmain.class. GetResource (gencfg). GetFile ()); Configurationparser CP=Newconfigurationparser (warnings); Configuration Config=NULL; Try{config=cp.parseconfiguration (configfile); } Catch(IOException e) {e.printstacktrace (); } Catch(xmlparserexception e) {e.printstacktrace (); } Defaultshellcallback Callback=Newdefaultshellcallback (overwrite); Mybatisgenerator Mybatisgenerator=NULL; Try{mybatisgenerator=Newmybatisgenerator (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 (); }    }}

So far, the Eclipse project drawing should look like this:


4. Run the main method of the test to generate MyBatis related code
Run the main method in the Genmain class and refresh the project, and you will find that the corresponding file has been generated in the respective package directory, fully compliant with the MyBatis rule, as follows:


5. Precautions
If you want to build something like example, you need to get rid of it in <table></table>

Enablecountbyexample= "false" enableupdatebyexample= "false" enabledeletebyexample= "false" enableselectbyexample= " False "Selectbyexamplequeryid=" false "

This is part of the configuration, which is used to generate example, which is generally useless for projects.

In addition, the generated SQL Mapper, and so on, just to single table additions and deletions, if you have multiple 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.

Program code
Like what:
Java-jar Mybatis-generator-core-1.3.2.jar-mbgconfiguration.xm-overwrite


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

Source code Download

MyBatis Real-Life tutorials (MyBatis in action) IX: Use of MyBatis code generation tools

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.