Introduction to MyBatis:
MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
Related reading: MyBatis introduction learning tutorial (I) - MyBatis quick start
Students who have used Mybatis know that for each project, they need to establish the corresponding database tables used in the database, add, delete, modify and check the xxxMapper.xml file, entity class xxx.java file, and other classes used to call the xxxMapper.java file for database operations. When I started learning Mybatis, I believe many people built these files manually. There is no doubt that if the project is larger, it is very inefficient to manually create these files. At this time, we can automatically generate these files through mybatis-generator. However, this tool generates related files in the form of a command line by default, so we can write an Ant script. Every time we need to create these files, we can automatically generate the Ant script in eclipse. The complete steps are as follows:
Import related jar packages
To use "mybatis-generator", you need to import the corresponding mybatis-generator-1.3.x.jar file in the lib of the web project. The download address on Github: mybatis-generator's jar package download
Second, configure the configuration file for mybatis-generator
(1) First, create several new packages in the project to store the corresponding files:
As can be seen from the above figure, src/main/java is used to store Java source code; src/main/env/dev is used to store configuration files in the development environment (such as: jdbc, cache, log, etc.); src/main/resources is used to store some common configuration files, where the Mapper.xml file we automatically generate is stored in this path; src/test/java represents the test code, and it doesn't matter here.
Note: How to add these source folders in eclipse?
(2) Create generatorConfig.xml and build_mybatis.xml in the project root directory:
These two files are the configuration file of "mybatis-generator" and the automated Ant script. The paths in the project are as follows:
i) generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!--Database Driver--><classPathEntrylocation="WebContent/WEB-INF/lib/mysql-connector-java-5.1.26-bin.jar" /><context id="DB2Tables" targetRuntime="MyBatis3"><commentGenerator><property name="suppressAllComments" value="true" /><!-- Whether to uncomment --><property name="suppressDate" value="true" /> <!-- Whether to generate comment generation timestamps --></commentGenerator><!-- Database connection information --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/ehcache_db" userId="root"password="root"></jdbcConnection><!-- Only one belongs to forceBigDecimals, default is false. If the field is accurate than 0, generate BigDecimal If the field is accurate, the total length is 10-18, generate Long; if the field is accurate, the total length is 5-9 generate Integer; if the field is accurate, the total length is less than 5 generate Short; If forceBigDecimals is true, generate BigDecimal uniformly --><javaTypeResolver><!-- Whether to use bigDecimal, false can automatically convert 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: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /><!-- Whether to call trim when set for fields of string type --><property name="trimStrings" value="true" /></javaModelGenerator><!-- Generate Mapper.xml file --><sqlMapGenerator targetPackage="sqlmaps"targetProject="src/main/resources"><!-- enableSubPackages: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- Generate Mapper.java file, i.e. dao layer --><javaClientGenerator type="XMLMAPPER"targetPackage="cn.zifangsky.mapper" targetProject="src/main/java"><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- To generate the table name in the database to be generated, to generate a Java and xml file corresponding to a table, you need to configure a section --><table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table></context></generatorConfiguration>
Note: Some places that need to be modified can be modified according to my comments above. Don’t forget the data-driven jar package
ii) build_mybatis.xml:
<project default="genfiles" basedir="."><property name="generated.source.dir" value="${basedir}" /><path id="ant.run.lib.path"><pathetic 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>There are two things to note in the above code: one is the jar package of "mybatis-generator", and the other is the corresponding "generatorConfig.xml" file
Note: If you are not familiar with Ant scripts, you can refer to the article I wrote: //www.VeVB.COM/article/87674.htm
Three tests
When performing the effect test, you only need to drag the file "build_mybatis.xml" into the Ant view, and then click to execute this script to automatically generate the file we need. Finally, refresh the project structure and you can see the file. The effect is as follows:
Note: The database data I used in tests:
SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(32) DEFAULT NULL,`password` varchar(64) DEFAULT NULL,`email` varchar(64) DEFAULT NULL,`birthday` date DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'admin', '123456', '[email protected]', '2000-01-02');INSERT INTO `user` VALUES ('2', 'test', '1234', '[email protected]', '1990-12-12');INSERT INTO `user` VALUES ('3', 'xxxx', 'xx', '[email protected]', '1723-06-21');The above is the method of using Mybatis Generator to quickly and automatically generate Model, Mapper and other files that the editor introduces to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!