A quick way to automatically generate model, mapper, and other files using MyBatis generator combined with ant scripts _java

Source: Internet
Author: User
Tags generator set time

MyBatis Introduction:

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

Related reading: MyBatis Introductory Learning Course (i)-mybatis QuickStart

The students who have used MyBatis know that the database tables used in each project need to establish their corresponding database, delete and check xxxmapper.xml files, Entity classes Xxx.java files and other classes are used to invoke Xxxmapper.java files for database operations. When I began to learn mybatis, I believe that many people have created these files by hand. There is no doubt that it is very inefficient to build these files manually if the project is larger, and then we can generate these files by Mybatis-generator. However, the tool defaults to generating the relevant files in the form of a command line, so we can create them automatically by writing an ant script that executes the ant script in eclipse every time we need to create them. The complete steps are as follows:

Import a related jar package

To use "mybatis-generator" you need to import a corresponding Mybatis-generator-1.3.x.jar file in the Web project's lib, GitHub download address: Mybatis-generator jar package Download

Configuration files for configuration Mybatis-generator

(1) First create a few new packages in the project to hold the corresponding files:

As can be seen from the above illustration, Src/main/java is used to store Java source code, Src/main/env/dev to store the configuration files (such as JDBC, cache, log, etc.) in the development environment, and src/main/resources to store some common configuration files. , where we automatically generate mapper.xml files that are stored in this path; Src/test/java represents the test code, no matter

Note: How do I add these source folders in eclipse?

(2) Create new Generatorconfig.xml and Build_mybatis.xml in the project root directory:

These two files are "mybatis-generator" profiles and automated ant scripts, and the path in the project is as follows:

i) Generatorconfig.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <!--database driver--> < Classpathentry location= "Webcontent/web-inf/lib/mysql-connector-java-5.1.26-bin.jar"/> <context id= " Db2tables "targetruntime=" MyBatis3 "> <commentGenerator> <property name=" suppressallcomments "value=" True '/><!--uncomment--> <property name= ' suppressdate ' value= ' true '/> <!--generate comment generation timestamp--> </comme ntgenerator> <!--database connection information--> <jdbcconnection driverclass= "Com.mysql.jdbc.Driver" JDBC: mysql://127.0.0.1:3306/ehcache_db "userid=" root "password=" root "> </jdbcConnection> <!-- Only one belongs to Forcebigdecimals, default false. If the field is more than 0 accurate, generate bigdecimal if the field is exactly 0, total length 10-18 generates long; If the field is 0, the total is 5-9 generates an integer; If the field is exactly 0, the total length is less than 5 to generate short; If Forcebigdecimals is true, unified generation of BigDecimal--> &LT;javatyperesolver> <!--whether to use BigDecimal, False automatically converts the following types (Long, Integer, short, etc.)--> <property name= " Forcebigdecimals "value= false"/> </javaTypeResolver> <!--generate Model.java file--> <javamodelgenerator Targetpackage= "Cn.zifangsky.model" targetproject= "Src/main/java" > <!--enablesubpackages: Let schema be the suffix of a package-- > <property name= "enablesubpackages" value= "false"/> <!--whether the trim call is made for string type fields at set time--> < Property Name= "Trimstrings" value= "true"/> </javaModelGenerator> <!--generate Mapper.xml file--> < Sqlmapgenerator targetpackage= "Sqlmaps" targetproject= "src/main/resources" > <!--enablesubpackages: Whether to have schema as the suffix of the package--> <property name= "Enablesubpackages" value= "false"/> </sqlMapGenerator> <!-- Generate Mapper.java file, the DAO layer--> <javaclientgenerator type= "Xmlmapper" targetpackage= "Cn.zifangsky.mapper" targetproject= "Src/main/java" > <property name= "enablesubpackages" value= "false"/> </javaclientgEnerator> <!--the table name in the database to be generated, generating a table corresponding Java and XML files requires configuring a--> <table tablename= "user" domainobjectname= "user" Enablecountbyexample= "false" enableupdatebyexample= "false" enabledeletebyexample= "false" enableselectbyexample= " False "Selectbyexamplequeryid=" false "> </table> </context> </generatorConfiguration>

Note: Some areas that need to be modified can be modified with reference to my comments above, and don't forget the data-driven jar pack

II) Build_mybatis.xml:

<project default= "Genfiles" basedir= "." >
<property name= "Generated.source.dir" value= "${basedir}"/> <path id=
"Ant.run.lib.path" >
<pathelement location= "${basedir}/webcontent/web-inf/lib/mybatis-generator-core-1.3.2.jar"/>
</path>
<target name= "genfiles" description= "Generate the Files" >
<taskdef name= "Mbgenerator "Classname=" Org.mybatis.generator.ant.GeneratorAntTask "classpathref=" Ant.run.lib.path "/>
< Mbgenerator overwrite= "true" configfile= "Generatorconfig.xml" verbose= "false" >
<propertyset>
<propertyref name= "Generated.source.dir"/>
</propertyset>
</mbgenerator>
</ Target>
</project>

The above code is two places to note: one is "mybatis-generator" jar package, the second is the need for the corresponding "Generatorconfig.xml" file

Note: If you are unfamiliar with the ant script, you can refer to the article I wrote: Http://www.jb51.net/article/87674.htm

Three Test

For effect testing, just drag the "build_mybatis.xml" file to the Ant view, and then click Execute to automatically generate the file we need, and finally to refresh the project structure can see the file, the effect is as follows:

Note: I tested the database data used:

SET foreign_key_checks=0;
------------------------------
--table structure for user
------------------------------
DROP table IF EXISTS ' user ';
CREATE TABLE ' user ' (
' id ' int () NOT NULL auto_increment,
' name ' varchar () DEFAULT null,
' password ' varch AR ($) default NULL,
' email ' varchar ($) default null,
' birthday ' date default null,
PRIMARY KEY (' id ') c12/>) Engine=innodb auto_increment=4 DEFAULT Charset=utf8;
------------------------------
--Records of user
------------------------------
INSERT into ' user ' VALUES (' 1 ', ' admin ', ' 123456 ', ' admin@qq.com ', ' 2000-01-02 ');
INSERT into ' user ' VALUES (' 2 ', ' Test ', ' 1234 ', ' test@zifangsky.cn ', ' 1990-12-12 ');
INSERT into ' user ' VALUES (' 3 ', ' xxxx ', ' xx ', ' xx@zifangsky.cn ', ' 1723-06-21 ');

The above is a small set to introduce the use of MyBatis generator combined with ant script rapid automatic generation model, mapper and other documents, hope for everyone to help, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.