Mybatis practical tutorial (mybatis in action) 9: Use of mybatis Code Generation Tool

Source: Internet
Author: User

The mybatis application requires a large number of configuration files. for hundreds of thousands of database tables, full manual configuration is a terrible workload. therefore, mybatis also officially launched a jar package for the mybatis code generation tool. today, it took a moment. According to the doc reference of mybatis generator, a usable version was initially configured. I also downloaded the source code. The mybatis code generation tool mainly has the following functions:
1. Generate a pojo that corresponds to the database structure
2. If a primary key exists, it can match the primary key.
3. If there is no primary key, you can use other fields to match
4. Dynamic select, update, and delete Methods
5. automatically generate the interface (that is, the previous Dao layer)
6. automatically generate SQL Mapper, add, delete, modify, and query various statement configurations, including dynamic where statement configurations
7. Generate example for Reference

The detailed process is described below

1. Create a test project and configure the mybatis code to generate a jar package.
: Http://code.google.com/p/mybatis/downloads/list? Can = 3 & Q = product % 3 dgenerator
MySQL driver download: http://dev.mysql.com/downloads/connector/j/
These jar packages are also included in the source code. You can download the source code at the end of the article. For more information, see.

Create a dynamic web project using eclipse.
Decompress the downloaded mybatis-generator-core-1.3.2-bundle.zip file, which has two directories: one directory is the file directory docs, mainly describes how to use this code generation tool, the other is the lib directory, the content inside 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 directory of the web project we just created. in this directory, add the MySQL driver jar package. because MySQL is used for testing.

2. Create a test table in the database
Create a category table for testing in the mybatis database (if the database mybatis is not available, create a table based on the previous series of articles. The database mybatis is already available)

Program code
Drop table if exists 'category ';
Create Table 'category '(
'Id' int (11) not null auto_increment,
'Catname' varchar (50) not null,
'Catdescription' varchar (200) default null,
Primary Key ('id ')
) Engine = InnoDB default charset = utf8;



3. Configure the configuration file of the mybatis code generation tool.
In the created web project, create the corresponding package, for example:
Com. yihaomen. Inter is used to store the mybatis interface object.
Com. yihaomen. mapper is used to store SQL ing and SQL statements corresponding to SQL mapper.
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 first. As a good application, these directories are also created regularly.

Generate a tool document based on the mybatis code. A configuration file is required, named mbgconfiguration. XML in the src directory. The configuration file is as follows:

Program code
<? 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 MySQL driver jar package. The absolute path is used. -->
<Classpathentry location = "D: \ work \ Java \ eclipse \ workspace \ mybatisgenerator \ webcontent \ WEB-INF \ Lib \ mysql-connector-java-5.1.22-bin.jar"/>

<Context ID = "yihaomen_mysql_tables" targetruntime = "mybatis3">

<! -- To prevent many comments in the generated code from being ugly, add the following configuration control -->
<Commentgenerator>
<Property name = "suppressallcomments" value = "true"/>
<Property name = "suppressdate" value = "true"/>
</Commentgenerator>
<! -- Annotation control completed -->

<! -- Database connection -->
<Jdbcconnection driverclass = "com. MySQL. JDBC. Driver"
Connectionurl = "JDBC: mysql: // 127.0.0.1: 3306/mybatis? Characterencoding = utf8"
Userid = "root"
Password = "password">
</Jdbcconnection>

<Javatyperesolver>
<Property name = "forcebigdecimals" value = "false"/>
</Javatyperesolver>

<! -- Model layer corresponding to the data table -->
<Javamodelgenerator targetpackage = "com. yihaomen. Model" targetproject = "src">
<Property name = "enablesubpackages" value = "true"/>
<Property name = "trimstrings" value = "true"/>
</Javamodelgenerator>

<! -- SQL mapper ing configuration file -->
<Sqlmapgenerator targetpackage = "com. yihaomen. mapper" targetproject = "src">
<Property name = "enablesubpackages" value = "true"/>
</Sqlmapgenerator>

<! -- In ibatis2, It is the DaO layer, but in mybatis3, it is actually the Mapper interface -->
<Javaclientgenerator type = "xmlmapper" targetpackage = "com. yihaomen. Inter" targetproject = "src">
<Property name = "enablesubpackages" value = "true"/>
</Javaclientgenerator>

<! -- To generate data tables, you must have one. -->
<Table schema = "mybatis" tablename = "category" domainobjectname = "category"
Enablecountbyexample = "false" enableupdatebyexample = "false"
Enabledeletebyexample = "false" enableselectbyexample = "false"
Selectbyexamplequeryid = "false">
</Table>

</Context>
</Generatorconfiguration>


Use a main method to test whether mybatis can be used to generate the model and SQL mapper corresponding to the newly created 'category 'table.
Create a package for com. yihaomen. Test and create a test class genmain under this package:

Program code
Package com. yihaomen. test;

Import java. Io. file;
Import java. Io. ioexception;
Import java. SQL. sqlexception;
Import java. util. arraylist;
Import java. util. List;

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 genmain {
Public static void main (string [] ARGs ){
List <string> warnings = new arraylist <string> ();
Boolean overwrite = true;
String gencfg = "/mbgconfiguration. xml ";
File configfile = new file (genmain. 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 = 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 ();
}
}
}


So far, the eclipse project engineering drawing should be as follows:


4. Run the main method of the test to generate code related to mybatis.
Run the main method in the genmain class and refresh the project. You will find that the corresponding file has been generated in the response under the respective package directories, which fully complies with the mybatis rules, as shown below:


5. Notes
If you want to generate something like example, you need to remove it from <Table> </table>.

Program code
Enablecountbyexample = "false" enableupdatebyexample = "false"
Enabledeletebyexample = "false" enableselectbyexample = "false"
Selectbyexamplequeryid = "false"


This part of configuration is used to generate example, which is useless to projects in general.

In addition, the generated SQL mapper only adds, deletes, modifies, and queries a single table. If you have a multi-table join operation, you can configure it manually. If you call the stored procedure, you also need to configure it manually. at this time, the workload is much less.

If you want to use the command line method for processing, you can also.

Program code
For example:
Java-jar mybatis-generator-core-1.3.2.jar-mbgconfiguration. XM-overwrite


In this case, you must use an absolute path. In addition, the targetproject configuration in the mbgconfiguration. xml configuration file must be an absolute path.

Mybatis practical tutorial (mybatis in action) 9: Use of 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.