MyBatis Generator (MBG) is a MyBatis code generator that helps us generate corresponding entity classes, XML mapper files, interfaces, and help classes based on the design of tables in the database (that is, we can use this class for simple crud operations). This avoids the need to manually create the corresponding classes and XML files for each table of data, which saves us a lot of time to develop functionality related to the business logic, but you still need handwritten SQL and objects for federated queries and stored procedures. I'll introduce the following two ways to generate the appropriate files based on Maven and the common Java project.
the way based on the MAVEN pluginFirst we should create a MAVEN project, Add the dependencies of the jar package we need to use in the Pom.xml file and add the Mybatis-generator-maven-plugin plugin, but note that the inside label specifies that the Generatorconfig.xml file position does not seem to work, and the default is to read src /main/resources the following XML file, put it in the other place does not work, and will be an error, said Generatorconfig.xml file can not find:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < Mybatis-generator.version>1.3.2</mybatis-generator.version> <mysql.version>5.1.13</
mysql.version> <mybatis.version>3.2.4</mybatis.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <
version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <ver sion>${mysql.version}</version> </dependency> <dependency> <groupid>org.mybatis .generator</groupid> <artifactId>mybatis-generator-core</artifactId> <version>${my Batis-generator.version}</version> </DEPendency> <dependency> <groupId>org.mybatis</groupId> <artifactid>mybatis<
;/artifactid> <version>${mybatis.version}</version> </dependency> </dependencies> <build> <finalName>mybatis-generator</finalName> <pluginManagement> &
Lt;plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${ mybatis-generator.version}</version> <!--database driver--> <dependencies&
Gt <dependency> <groupId>mysql</groupId> <artifa Ctid>mysql-connector-java</artifactid> <version>${mysql.version}</versioN> </dependency> </dependencies> <!--automatic Generate--> <executions> <execution> ; id>generate MyBatis artifacts</id> <goals> ;goal>generate</goal> </goals> <configuration>
; <!--The specified file location does not seem to work, always default to read Src/main/resources/generatorconfig.xml file--> <configurati Onfile>src/main/resources/generatorconfig.xml</configurationfile> <!--allowed to move generated text Pieces--> <verbose>true</verbose> <!--allow overwriting of generated File--> <overwrite>true</overwrite>;/configuration> </execution> </executions>
;/plugin> <plugin> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <configuration>
<source>1.5</source> <target>1.5</target> <encoding>UTF-8</encoding> </configuration> </plugin > </plugins> </pluginManagement> </build>
2. The Generatorconfig.xml file mentioned above also needs our own configuration, which mainly configures the configuration of the connection database and the generated file configuration information as well as the most important is the table or attempt of the entity class that we want to generate.
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en
G/dtd/mybatis-generator-config_1_0.dtd "> <!--This profile describes how the plug-in needs to be generated and generates the corresponding package name, path, and so on. It is also important that we generate the entity classes corresponding to the table or try to--> <generatorConfiguration> <properties resource= "Mybatis_ Generator.properties "/> <context id= MBG" targetruntime= "MyBatis3" defaultmodeltype= "conditional" > & lt;! --note the order of the following labels: property*,plugin*,commentgenerator?,jdbcconnection, JAVATYPERESOLVER?,JAVAMODELGENERATOR,SQLM Apgenerator, javaclientgenerator?,table+--> <plugin type= "Org.mybatis.generator.plugins.Eq Ualshashcodeplugin "/> <!--this plugin adds equals and Hashcode methods to the Java model objects generated by MBG--> <plugin type=" Org.myb Atis.generator.plugins.EqualsHashCodePlugin "/> <commentGenerator> <!--whether to remove automatically generated comments true: Yes : false: No-->
<property name= "Suppressallcomments" value= "false"/> <!--do not want the generated annotation to contain a timestamp--> <property name= "Suppressdate" value= "true"/> <!--Automatically create a construction method for each generated class-->
Roperty name= "constructorbased" value= "false"/> </commentGenerator> <!--database connection--> <jdbcconnection driverclass= "${jdbc_driver}" connectionurl= "${jdbc_url" ${jdbc_username} "password=" ${jdbc_password} "> </jdbcConnection> <!--Specifies that the generated type is JAV Type A, avoid type fields such as number in the database--> <javaTypeResolver> <property name= "Forcebigdecimals value=" Fals E "/> </javaTypeResolver> <!--generate model models, corresponding packages, where you can specify specific paths, such as/PROJECTNAME/SRC, or you can use Maven to derive from dynamic generation- -> <javamodelgenerator targetpackage= "${modelpackage}" targetproject= "${targetproject}" > < !--on the basis of targetpackage, the rootAccording to the database schema regenerated into a layer of package, the resulting class is placed under this package, the default is False--> <property name= "Enablesubpackages" value= "true"/ > <!--settings in the Getter method, call the Trim () method on the String Type field--> <property name= "Trimstrings value=" tr UE "/> </javaModelGenerator> <!--corresponding XML mapper file--> <sqlmapgenerator targetpack Age= ' ${sqlmapperpackage} ' targetproject= ' ${targetproject} ' > <property name= ' enablesubpackages ' value= ' t Rue "/> </sqlMapGenerator> <!--corresponding DAO interface--> <javaclientgenerator type=" Xmlmappe R "targetpackage=" ${daomapperpackage} "targetproject=" ${targetproject} "> <property name=" EnableSubPacka Ges "value=" true "/> </javaClientGenerator> <!--table names correspond to generated entities--> <table Tabl Ename= "Ecjtu_tab_user" domainobjectname= "user"/> <!--enablecountbyexample= "false" enableupdatebyexample= "F Alse "EnabledeleTebyexample= "false" enableselectbyexample= "false" Selectbyexamplequeryid= "false" > Specifies whether to generate the corresponding method for manipulating the database--> </context> </generatorConfiguration>
Note: There are two places to note in this profile:
A, the comments in the configuration file should be:<!--This is a comment, you can't nest in annotations-such as:<!----this-is a comment, otherwise the runtime will prompt an error message.
B, the label inside the elements are in order, if the order of chaos will also error, the order is:
Property-->plugin-->commentgenerator-->jdbcconnection-->
javatyperesolver--> Javamodelgenerator-->sqlmapgenerator-->
javaclientgenerator-->table+
3. For the Mybatis_ introduced in the Generatorconfig.xml file Generator.properties file, which is primarily the database connection information and the directory information of the generated files, we can create the file in the same directory as the Generatorconfig.xml:
#数据库配置
#jdbc: Mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=utf-8
JDBC_URL=JDBC : Mysql://localhost:3306/test
jdbc_driver=com.mysql.jdbc.driver
jdbc_username=root
jdbc_password= Admin
#执行: right mouse Run as---->maven build---->goals:mybatis-generator:generate
#输出目录
targetproject= Src/main/java
#modelPackage, sqlmapperpackage,daomapperpackage usually consistent
modelpackage= Com.ecjtu.generator.entitys
sqlmapperpackage=com.ecjtu.generator.entitys
daomapperpackage= Com.ecjtu.generator.entitys
4. After you have created the above three files, we can then create a package path to execute, which is to create the Mybatis_ under Src/main/java The package path for the build entity specified in the Generator.properties file, the Com.ecjtu.generator.entitys package specified above, and then right-pom.xml the file, Run As-->maven Build-->goals:mybatis-generator: Refresh the following item after performing this operation the files you generated are all there. Common Java Project generation entities
This way is more than the Maven plug-in way that we write a class ourselves in the main method to read the Generatorconfig.xml file, and then to generate the corresponding file.
Since there is no use of Maven Plug-ins, but also a common Java project, then we need to manually introduce the relevant jar package, under SRC Create a new Lib folder, the use of the jar package copied to the folder below, the introduction of the jar package as follows:
After the jar package is introduced, the other configuration files are similar to the way you use Maven, as well as configuring Generatorconfig.xml files and mybatis_generator.properties files. The only difference between the Generatorconfig.xml file and the MAVEN approach is the need to indicate the location of the driver package outside the label:
<!--use an absolute path, or you may not find a jar pack-->
<classpathentry location= "E:\JavaStudy\DevlopeEnvironment\workspace\ Mybatisgeneratormain\lib\mysql-connector-java-5.1.22-bin.jar "/>
3. The last one is to create a class, read the Generatorconfig.xml file in the main method, and then generate the corresponding file
Package com.ecjtu.generator.main;
Import Java.io.File;
Import java.io.IOException;
Import Java.net.URL;
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;//If you have already generated whether to overwrite String gencfg = "/generatorconfig.xml";//path of configuration file: default to src URL u below
RL = GenMain.class.getResource (GENCFG);
String file = Url.getfile ();
File ConfigFile = new file (file); Configurationparser cfgparser = new Configurationparser (warnings);Config file parser Configuration config = null;
try {config = cfgparser.parseconfiguration (configfile);
catch (IOException e) {e.printstacktrace ();
catch (Xmlparserexception e) {e.printstacktrace ();
} Defaultshellcallback callback = new Defaultshellcallback (overwrite);
Mybatisgenerator generator = null;
try {generator = new Mybatisgenerator (config, callback, warnings);
catch (Invalidconfigurationexception e) {e.printstacktrace ();
try {generator.generate (null); System.out.println ("MyBatis code generation succeeded ...")
");
catch (SQLException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
catch (Interruptedexception e) {e.printstacktrace ();
}
}
}
4. Finally, the right key to execute the Java program, and then refresh, the resulting file appears.
Here, MyBatis based on Maven and the common Java Engineering generation entities are introduced in two ways .....