Mybatis generator
Its main function is easy and fast to create good Dao, entry, xml speeds development, the use of the OK configured according to the rules provided by its
There is also an important development scenarios, the development process, the operation of the database certainly a lot like what the new field, as long as you originally set the auto-generated code is deleted, re-generates a, which is the perfect solution, but to do this premise is that you do not have to change the code after generation, just use. You do not need to write code that developers want to manually change the code everywhere, but also that change leak place.
In fact, this is also a wide variety of implementations, write a relatively common
The main flow
The first step: add dependencies
Mainly jdbc and generator
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
Step Two: Configure generatorConfig.xml
This document is primarily come from, where to go descriptions, there are some special configuration requirements
<? Xml Version = "1.0" encoding = "UTF-8" ?> <! DOCTYPE generatorConfiguration the PUBLIC "- // mybatis.org//DTD the Configuration MyBatis Generator 1.0 // EN" "http://mybatis.org/dtd /mybatis-generator-config_1_0.dtd " > < generatorConfiguration > < context the above mentioned id =" DB2Tables " targetRuntime =" MyBatis 3 " > <-! generate mysql sql plugin with this page can write your own, -> < plugin of the type = "generator.MysqlPaginationPlugin" /> < plugin type = "org.mybatis.generator.plugins.ToStringPlugin" /> <plugin of the type = "org.mybatis.generator.plugins.SerializablePlugin" /> <-! Self annotation rules defined, inheritance DefaultCommentGenerator rewrite some way -> < commentGenerator of the type = "generator.NewbatisGenerator" > <-! Are removal dates automatically generated annotation true: is: to false: NO -> < Property name = "suppressDate" value = "true" /> <-! if true remove all auto-generated comments: is: to false: NO - > < Property name = "suppressAllComments" value = "to true" /> </commentGenerator> <jdbcConnection driverClass = "com.mysql.jdbc.Driver" the connectionURL = "JDBC: MySQL: // database address" the userId = "username" password = "password" > </ JdbcConnection > <-! generating entity class storage position -> < javaModelGenerator targetPackage = "package name (com.generator.test.entity)" targetProject = "project to address \ the Java (D: \ Workspace \ src \ main \ the Java)" > < Property name = "enableSubPackages" value = "to true " /> <property name="trimStrings" value= "to true" /> </ javaModelGenerator > ! <- generate a map file location -> < sqlMapGenerator targetPackage = "package name (com.generator.test.mapper)" targetProject = "project to address \ java (D: \ Workspace \ the src \ main \ Java) " > < Property name =" enableSubPackages " value =" to true " /> </ sqlMapGenerator > <-! generated Dao class storage position -> < javaClientGenerator type =" XMLMAPPER " targetPackage = "package name (com.generator.test.dao)" targetProject= "Item address to the \ Java (D: \ Workspace \ the src \ main \ Java)" > < Property name = "enableSubPackages," value = "to true" /> </ javaClientGenerator > < Table tableName = "table" domainObjectName = " generating entity class name " > </ Table > </ context > </ generatorConfiguration >
The third step: mainly depends on your personal needs, annotation, pagination what's not what's required, you can override several methods to be rehabilitated
The main few examples
Modify NewbatisGenerator to comments
public class NewbatisGenerator extends DefaultCommentGenerator { private Properties properties; private Properties systemPro; private boolean suppressDate; private boolean suppressAllComments; private String currentDateStr; public NewbatisGenerator() { super(); properties = new Properties(); systemPro = System.getProperties(); suppressDate = false; suppressAllComments = false; currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()); } /** * 对类的注解 * @param topLevelClass * @param introspectedTable */ @Override public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { topLevelClass.addJavaDocLine("/**"); topLevelClass.addJavaDocLine(" * 这是MyBatis Generator自动生成的Model Class."); StringBuilder sb = new StringBuilder(); sb.append(" * 对应的数据表是 : "); sb.append(introspectedTable.getFullyQualifiedTable()); topLevelClass.addJavaDocLine(sb.toString()); String tableRemarks = introspectedTable.getRemarks(); if (!StringUtils.isEmpty(tableRemarks)) { sb.setLength(0); sb.append(" * 数据表注释 : "); sb.append(tableRemarks); topLevelClass.addJavaDocLine(sb.toString()); } sb.setLength(0); sb.append(" * @author "); sb.append(systemPro.getProperty("user.name")); topLevelClass.addJavaDocLine(sb.toString()); String curDateString = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()); sb.setLength(0); sb.append(" * @date "); sb.append(curDateString); topLevelClass.addJavaDocLine(sb.toString()); topLevelClass.addJavaDocLine(" */"); } /** * 生成的实体增加字段的中文注释 */ public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { if (suppressAllComments) { return; } StringBuilder sb = new StringBuilder(); field.addJavaDocLine("/**"); sb.append(" * "); sb.append(introspectedColumn.getRemarks()); field.addJavaDocLine(sb.toString().replace("\n", " ")); field.addJavaDocLine(" */"); } }
Add MysqlPaginationPlugin paging automatically generated with pagination plug-in
public class MysqlPaginationPlugin extends PluginAdapter { public MysqlPaginationPlugin() {} public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { this.addLimit(topLevelClass, introspectedTable, "limitStart"); this.addLimit(topLevelClass, introspectedTable, "limitSize"); return super.modelExampleClassGenerated(topLevelClass, introspectedTable); } public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { XmlElement isNotNullElement = new XmlElement("if"); isNotNullElement .addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0")); isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}")); element.addElement(isNotNullElement); return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable); } public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { XmlElement isNotNullElement = new XmlElement("if"); isNotNullElement .addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0")); isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}")); element.addElement(isNotNullElement); return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable); } private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) { CommentGenerator commentGenerator = this.context.getCommentGenerator(); Field field = new Field(); field.setVisibility(JavaVisibility.PROTECTED); field.setType(PrimitiveTypeWrapper.getIntegerInstance()); field.setName(name); commentGenerator.addFieldComment(field, introspectedTable); topLevelClass.addField(field); char c = name.charAt(0); String camel = Character.toUpperCase(c) + name.substring(1); Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setName("set" + camel); method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name)); StringBuilder sb = new StringBuilder(); sb.append("this."); sb.append(name); sb.append(" = "); sb.append(name); sb.append(";"); method.addBodyLine(sb.toString()); commentGenerator.addGeneralMethodComment(method, introspectedTable); topLevelClass.addMethod(method); Method getterMethod = AbstractJavaGenerator.getGetter(field); commentGenerator.addGeneralMethodComment(getterMethod, introspectedTable); topLevelClass.addMethod(getterMethod); } public Boolean the validate (List <String> Represents warnings) { return to true ; } / ** * generated mapper.xml, the file will be cleared rewritten * * / @Override public Boolean sqlMapGenerated (GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) { sqlMap. setMergeable ( to false ); return Super .sqlMapGenerated (sqlMap, introspectedTable); } }
The final step: Run generation
These are some of the official website
public class Generator { public static void main(String[] args) throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }
This relatively simple, personalized is also good, worthy of recommendation
Please indicate the source : https://www.cnblogs.com/zhouguanglin/p/11239583.html