【Java】 rapid-generator 代码生成器

  rapid-generator是一个生成器引擎,让你可以专注与代码生成器模板的编写, 可以生成如ibatis,ibatis3,hibernate,spring_mvc,struts2等等代码.

  rapid-generator是设置Freemarker模版,JDBC获取数据库信息,将数据库信息和模版绑定,输出代码文件

  
 

rapid-generator 使用

  1、新建一个Maven项目

    

  2、引入rapid-generator相关依赖

 1 <project xmlns="http://maven.apache.org/POM/4.0.0"
 2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <groupId>com.test</groupId>
 6     <artifactId>test-rapid-generator</artifactId>
 7     <version>0.0.1-SNAPSHOT</version>
 8 
 9 
10     <dependencies>
11         <!-- 代码生成工具 -->
12         <dependency>
13             <groupId>com.googlecode.rapid-framework</groupId>
14             <artifactId>rapid-generator</artifactId>
15             <version>4.0.6</version>
16         </dependency>
17 
18 
19         <!-- mysql数据库 -->
20         <dependency>
21             <groupId>mysql</groupId>
22             <artifactId>mysql-connector-java</artifactId>
23             <version>8.0.13</version>
24         </dependency>
25 
26         <!-- freemarker -->
27         <dependency>
28             <groupId>org.freemarker</groupId>
29             <artifactId>freemarker</artifactId>
30             <version>2.3.28</version>
31         </dependency>
32 
33         <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
34         <dependency>
35             <groupId>com.h2database</groupId>
36             <artifactId>h2</artifactId>
37             <version>1.2.135</version>
38         </dependency>
39 
40         <!-- 代码生成器扩展包 -->
41         <dependency>
42             <groupId>com.googlecode.rapid-framework</groupId>
43             <artifactId>rapid-generator-ext</artifactId>
44             <version>4.0.6</version>
45         </dependency>
46 
47         <!-- 代码生成器模板,模板根目录通过 classpath:generator/template/rapid 可以引用 -->
48         <dependency>
49             <groupId>com.googlecode.rapid-framework</groupId>
50             <artifactId>rapid-generator-template</artifactId>
51             <version>4.0.6</version>
52         </dependency>
53 
54         <dependency>
55             <groupId>junit</groupId>
56             <artifactId>junit</artifactId>
57             <version>3.8.1</version>
58             <scope>test</scope>
59         </dependency>
60     </dependencies>
61 </project>
View Code

  3、增加log4j.properties配置文件

1  ### 设置###
2 log4j.rootLogger = debug,stdout,D,E
3  
4 ### 输出信息到控制抬 ###
5 log4j.appender.stdout = org.apache.log4j.ConsoleAppender
6 log4j.appender.stdout.Target = System.out
7 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
8 log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
View Code

  4、增加generator.xml配置文件,配置代码生成器相关属性

 1 <?xml version="1.0" encoding="GBK"?>  
 2 <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
 3 <properties>  
 4     <comment>  
 5         代码生成器配置文件:   
 6         1.会为所有的property生成property_dir属性,如pkg=com.company => pkg_dir=com/company  
 7         2.可以引用环境变量: ${env.JAVA_HOME} or System.properties: ${user.home},property之间也可以相互引用  
 8     </comment>  
 9     
10     <entry key="author">God</entry> 
11       
12     <entry key="basepackage">com.test</entry>  
13       
14     <!-- jsp namespace: web/${namespace}/${className}/list.jsp -->  
15     <entry key="namespace">pages</entry>  
16     
17     <!-- 对应修改下Constants.Mybatis.NAMESPACE_PREFIX -->
18     <entry key="namespace_prefix">com.test.model</entry>
19       
20     <entry key="outRoot">/Users/H__D/Desktop/generator-output</entry>
21   
22     <!-- 需要移除的表名前缀,使用逗号进行分隔多个前缀,示例值: t_,v_ -->  
23     <entry key="tableRemovePrefixes"></entry>  
24       
25     <entry key="jdbc_username">admin</entry>  
26     <entry key="jdbc_password">admin</entry>  
27           
28     <!-- oracle需要指定jdbc.schema,其它数据库忽略此项配置  -->  
29     <entry key="jdbc_schema"></entry>  
30     <entry key="jdbc_catalog"></entry>  
31       
32     <!-- 数据库类型映射  -->  
33     <entry key="java_typemapping.java.sql.Timestamp">java.util.Date</entry>  
34     <entry key="java_typemapping.java.sql.Date">java.util.Date</entry>  
35     <entry key="java_typemapping.java.sql.Time">java.util.Date</entry>    
36     <entry key="java_typemapping.java.lang.Byte">Integer</entry>  
37     <entry key="java_typemapping.java.lang.Short">Integer</entry>  
38     <entry key="java_typemapping.java.math.BigDecimal">Long</entry>  
39   
40     <!-- H2 -->  
41     <!-- <entry key="jdbc.url">jdbc:h2:tcp://localhost/test</entry>  
42     <entry key="jdbc.driver">org.h2.Driver</entry>  
43     -->  
44           
45     <entry key="jdbc_url">jdbc:mysql://127.0.0.1/god?allowPublicKeyRetrieval=true</entry>  
46     <entry key="jdbc_driver">com.mysql.jdbc.Driver</entry>  
47   
48     <!-- Oracle  jdbc:oracle:oci:@tnsname_devdb  
49     <entry key="jdbc.url">jdbc:oracle:thin:@192.168.0.177:1521:[sid]</entry>  
50     <entry key="jdbc.driver">oracle.jdbc.driver.OracleDriver</entry>  
51     -->  
52       
53     <!-- SQLServer2000   
54     <entry key="jdbc.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=[database]</entry>  
55     <entry key="jdbc.driver">com.microsoft.jdbc.sqlserver.SQLServerDriver</entry>  
56     -->  
57       
58     <!-- SQLServer2005   
59     <entry key="jdbc.url">jdbc:sqlserver://192.168.0.98:1433;DatabaseName=[database]</entry>  
60     <entry key="jdbc.driver">com.microsoft.sqlserver.jdbc.SQLServerDriver</entry>  
61     -->  
62   
63     <!-- JTDs for SQLServer   
64     <entry key="jdbc.url">jdbc:jtds:sqlserver://192.168.0.102:1433/[database];tds=8.0;lastupdatecount=true</entry>  
65     <entry key="jdbc.driver">net.sourceforge.jtds.jdbc.Driver</entry>  
66     -->  
67   
68     <!-- PostgreSql  
69    <entry key="jdbc.url">jdbc:postgresql://localhost/[database]</entry>  
70    <entry key="jdbc.driver">org.postgresql.Driver</entry>  
71     -->  
72       
73     <!-- Sybase  
74    <entry key="jdbc.url">jdbc:sybase:Tds:localhost:5007/[database]</entry>  
75    <entry key="jdbc.driver">com.sybase.jdbc.SybDriver</entry>  
76     -->  
77       
78     <!-- DB2   
79     <entry key="jdbc.url">jdbc:db2://localhost:5000/[database]</entry>  
80     <entry key="jdbc.driver">com.ibm.db2.jdbc.app.DB2Driver</entry>  
81     -->  
82       
83     <!-- HsqlDB   
84     <entry key="jdbc.url">jdbc:hsqldb:mem:generatorDB</entry>  
85     <entry key="jdbc.driver">org.hsqldb.jdbcDriver</entry>  
86     -->  
87       
88     <!-- Derby   
89     <entry key="jdbc.url">jdbc:derby://localhost/databaseName</entry>  
90     <entry key="jdbc.driver">org.apache.derby.jdbc.ClientDriver</entry>   
91     -->  
92   
93 </properties> 

  5、配置代码模版文件

    a、${className}Dao.java

 1 <#include "/java_copyright.include">
 2 <#assign className = table.className>   
 3 <#assign classNameLower = className?uncap_first>   
 4 package ${basepackage}.dao;
 5 
 6 <#include "/java_imports.include">
 7 
 8 import java.util.List;
 9 import org.apache.ibatis.annotations.Param;
10 
11 import ${basepackage}.model.${className};
12 import ${basepackage}.model.${className}Example;
13 
14 
15 /**
16  * ${table.remarks } DAO层
17  * 
18  * @author ${author}
19  * @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
20  */
21 public interface ${className}Dao {
22     
23     /**
24      * 统计记录-根据示例条件
25      */
26     long countByExample(${className}Example example);
27 
28     /**
29      * 删除记录-根据示例条件
30      */
31     int deleteByExample(${className}Example example);
32 
33     /**
34      * 删除记录-根据主键
35      */
36     int deleteByPrimaryKey(Integer id);
37 
38     /**
39      * 插入记录-完全插入
40      */
41     int insert(${className} record);
42 
43     /**
44      * 插入记录-选择性插入
45      */
46     int insertSelective(${className} record);
47 
48     /**
49      * 查询记录-根据示例条件
50      */
51     List<${className}> selectByExample(${className}Example example);
52 
53     /**
54      * 查询记录-根据主键
55      */
56     ${className} selectByPrimaryKey(Integer id);
57 
58     /**
59      * 更新记录-根据示例条件选择性更新
60      */
61     int updateByExampleSelective(@Param("record") ${className} record, @Param("example") ${className}Example example);
62 
63     /**
64      * 更新记录-根据示例条件更新
65      */
66     int updateByExample(@Param("record") ${className} record, @Param("example") ${className}Example example);
67 
68     /**
69      * 更新记录-根据主键选择性更新
70      * @return
71      */
72     int updateByPrimaryKeySelective(${className} record);
73 
74     /**
75      * 更新记录-根据主键更新
76      * @return
77      */
78     int updateByPrimaryKey(${className} record);
79     
80 }

    b、${className}.java

 1 <#include "/macro.include"/>
 2 <#include "/java_copyright.include">
 3 <#assign className = table.className>   
 4 <#assign classNameLower = className?uncap_first> 
 5 <#assign hasDateType = false>
 6 package ${basepackage}.model;
 7 
 8 <#list table.columns as column>
 9 <#if column.isDateTimeColumn>
10     <#assign hasDateType = true>
11 </#if>
12 </#list>
13 import java.io.Serializable;
14 <#if hasDateType>
15 import java.util.Date;
16 </#if>
17 
18 <#include "/java_imports.include">
19 
20 /**
21  * ${table.remarks } 实体类
22  * 
23  * @author ${author}
24  * @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
25  */
26 public class ${className} implements java.io.Serializable{
27     
28     private static final long serialVersionUID = 1L;    
29     
30     <#list table.columns as column>
31     /**
32      * ${column.columnAlias!} 
33      */
34     private ${column.simpleJavaType} ${column.columnNameLower};
35     </#list>
36     
37 <@generateJavaColumns/>
38 
39 }
40 
41 <#macro generateJavaColumns>
42     <#list table.columns as column>
43         
44     public void set${column.columnName}(${column.simpleJavaType} value) {
45         this.${column.columnNameLower} = value;
46     }
47     
48     public ${column.simpleJavaType} get${column.columnName}() {
49         return this.${column.columnNameLower};
50     }
51     </#list>
52 </#macro>

   c、${className}Example.java

  1 <#include "/macro.include"/>
  2 <#include "/java_copyright.include">
  3 <#assign className = table.className>   
  4 <#assign classNameLower = className?uncap_first> 
  5 <#assign hasDateType = false>
  6 package ${querypackage};
  7 
  8 <#list table.columns as column>
  9 <#if column.isDateTimeColumn>
 10     <#assign hasDateType = true>
 11 </#if>
 12 </#list>
 13 import java.io.Serializable;
 14 <#if hasDateType>
 15 import java.util.Date;
 16 </#if>
 17 import java.util.ArrayList;
 18 import java.util.List;
 19 
 20 <#include "/java_imports.include">
 21 
 22 /**
 23  * ${table.remarks } 示例类
 24  * 
 25  * @author ${author}
 26  * @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
 27  */
 28 public class ${className}Example implements java.io.Serializable{
 29     
 30     private static final long serialVersionUID = 1L;    
 31     
 32     protected String orderByClause;
 33     
 34     protected boolean distinct;
 35     
 36     protected List<Criteria> oredCriteria;
 37     
 38     public ${className}Example() {
 39         oredCriteria = new ArrayList<Criteria>();
 40     }
 41     
 42     public void setOrderByClause(String orderByClause) {
 43         this.orderByClause = orderByClause;
 44     }
 45     
 46     public String getOrderByClause() {
 47         return orderByClause;
 48     }
 49     
 50     public void setDistinct(boolean distinct) {
 51         this.distinct = distinct;
 52     }
 53     
 54     public boolean isDistinct() {
 55         return distinct;
 56     }
 57     
 58     public List<Criteria> getOredCriteria() {
 59         return oredCriteria;
 60     }
 61     
 62     public void or(Criteria criteria) {
 63         oredCriteria.add(criteria);
 64     }
 65     
 66     public Criteria or() {
 67         Criteria criteria = createCriteriaInternal();
 68         oredCriteria.add(criteria);
 69         return criteria;
 70     }
 71     
 72     public Criteria createCriteria() {
 73         Criteria criteria = createCriteriaInternal();
 74         if (oredCriteria.size() == 0) {
 75             oredCriteria.add(criteria);
 76         }
 77         return criteria;
 78     }
 79     
 80     protected Criteria createCriteriaInternal() {
 81         Criteria criteria = new Criteria();
 82         return criteria;
 83     }
 84     
 85     public void clear() {
 86         oredCriteria.clear();
 87         orderByClause = null;
 88         distinct = false;
 89     }
 90     
 91     protected abstract static class GeneratedCriteria {
 92         protected List<Criterion> criteria;
 93     
 94         protected GeneratedCriteria() {
 95             super();
 96             criteria = new ArrayList<Criterion>();
 97         }
 98     
 99         public boolean isValid() {
100             return criteria.size() > 0;
101         }
102     
103         public List<Criterion> getAllCriteria() {
104             return criteria;
105         }
106     
107         public List<Criterion> getCriteria() {
108             return criteria;
109         }
110     
111         protected void addCriterion(String condition) {
112             if (condition == null) {
113                 throw new RuntimeException("Value for condition cannot be null");
114             }
115             criteria.add(new Criterion(condition));
116         }
117     
118         protected void addCriterion(String condition, Object value, String property) {
119             if (value == null) {
120                 throw new RuntimeException("Value for " + property + " cannot be null");
121             }
122             criteria.add(new Criterion(condition, value));
123         }
124     
125         protected void addCriterion(String condition, Object value1, Object value2, String property) {
126             if (value1 == null || value2 == null) {
127                 throw new RuntimeException("Between values for " + property + " cannot be null");
128             }
129             criteria.add(new Criterion(condition, value1, value2));
130         }
131         
132         <#list table.columns as column>
133         public Criteria and${column.columnName}IsNull() {
134             addCriterion("${column.sqlName} is null");
135             return (Criteria) this;
136         }
137         public Criteria and${column.columnName}IsNotNull() {
138             addCriterion("${column.sqlName} is not null");
139             return (Criteria) this;
140         }
141         public Criteria and${column.columnName}EqualTo(${column.simpleJavaType} value) {
142             addCriterion("${column.sqlName} =", value, "${column.columnNameLower}");
143             return (Criteria) this;
144         }
145         public Criteria and${column.columnName}NotEqualTo(${column.simpleJavaType} value) {
146             addCriterion("${column.sqlName} <>", value, "${column.columnNameLower}");
147             return (Criteria) this;
148         }
149         public Criteria and${column.columnName}GreaterThan(${column.simpleJavaType} value) {
150             addCriterion("${column.sqlName} >", value, "${column.columnNameLower}");
151             return (Criteria) this;
152         }
153         public Criteria and${column.columnName}GreaterThanOrEqualTo(${column.simpleJavaType} value) {
154             addCriterion("${column.sqlName} >=", value, "${column.columnNameLower}");
155             return (Criteria) this;
156         }
157         public Criteria and${column.columnName}LessThan(${column.simpleJavaType} value) {
158             addCriterion("${column.sqlName} <", value, "${column.columnNameLower}");
159             return (Criteria) this;
160         }
161         
162         public Criteria and${column.columnName}LessThanOrEqualTo(${column.simpleJavaType} value) {
163             addCriterion("${column.sqlName} <=", value, "${column.columnNameLower}");
164             return (Criteria) this;
165         }
166         
167         <#if column.isStringColumn>
168         public Criteria and${column.columnName}Like(String value) {
169             addCriterion("${column.sqlName} like", value, "${column.columnNameLower}");
170             return (Criteria) this;
171         }
172         
173         public Criteria and${column.columnName}NotLike(String value) {
174             addCriterion("${column.sqlName} not like", value, "${column.columnNameLower}");
175             return (Criteria) this;
176         }
177         
178         </#if>
179         public Criteria and${column.columnName}In(List<${column.simpleJavaType}> values) {
180             addCriterion("${column.sqlName} in", values, "${column.columnNameLower}");
181             return (Criteria) this;
182         }
183         
184         public Criteria and${column.columnName}NotIn(List<${column.simpleJavaType}> values) {
185             addCriterion("${column.sqlName} not in", values, "${column.columnNameLower}");
186             return (Criteria) this;
187         }
188         
189         public Criteria and${column.columnName}Between(${column.simpleJavaType} value1, ${column.simpleJavaType} value2) {
190             addCriterion("${column.sqlName} between", value1, value2, "${column.columnNameLower}");
191             return (Criteria) this;
192         }
193         
194         public Criteria and${column.columnName}NotBetween(${column.simpleJavaType} value1, ${column.simpleJavaType} value2) {
195             addCriterion("${column.sqlName} not between", value1, value2, "${column.columnNameLower}");
196             return (Criteria) this;
197         }
198         </#list>
199     }
200     
201     public static class Criteria extends GeneratedCriteria {
202     
203         protected Criteria() {
204             super();
205         }
206     }
207     
208     public static class Criterion {
209         private String condition;
210     
211         private Object value;
212     
213         private Object secondValue;
214     
215         private boolean noValue;
216     
217         private boolean singleValue;
218     
219         private boolean betweenValue;
220     
221         private boolean listValue;
222     
223         private String typeHandler;
224     
225         public String getCondition() {
226             return condition;
227         }
228     
229         public Object getValue() {
230             return value;
231         }
232     
233         public Object getSecondValue() {
234             return secondValue;
235         }
236     
237         public boolean isNoValue() {
238             return noValue;
239         }
240     
241         public boolean isSingleValue() {
242             return singleValue;
243         }
244     
245         public boolean isBetweenValue() {
246             return betweenValue;
247         }
248     
249         public boolean isListValue() {
250             return listValue;
251         }
252     
253         public String getTypeHandler() {
254             return typeHandler;
255         }
256     
257         protected Criterion(String condition) {
258             super();
259             this.condition = condition;
260             this.typeHandler = null;
261             this.noValue = true;
262         }
263     
264         protected Criterion(String condition, Object value, String typeHandler) {
265             super();
266             this.condition = condition;
267             this.value = value;
268             this.typeHandler = typeHandler;
269             if (value instanceof List<?>) {
270                 this.listValue = true;
271             } else {
272                 this.singleValue = true;
273             }
274         }
275     
276         protected Criterion(String condition, Object value) {
277             this(condition, value, null);
278         }
279     
280         protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
281             super();
282             this.condition = condition;
283             this.value = value;
284             this.secondValue = secondValue;
285             this.typeHandler = typeHandler;
286             this.betweenValue = true;
287         }
288     
289         protected Criterion(String condition, Object value, Object secondValue) {
290             this(condition, value, secondValue, null);
291         }
292     }
293 }
View Code

   d、${className}Mapper.xml

  1 <#include "/macro.include"/>
  2 <#assign className = table.className>   
  3 <#assign classNameFirstLower = table.classNameFirstLower>   
  4 <?xml version="1.0" encoding="UTF-8" ?>
  5 <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
  6 
  7 <#macro mapperEl value>${r"#{"}${value}}</#macro>
  8 <#macro mapperElJ value>${r"${"}${value}}</#macro>
  9 <#macro mapperElP value jdbcType>${r"#{"}${value},jdbcType=${jdbcType}}</#macro>
 10 <#macro namespace>${basepackage}.dao.${className}Dao</#macro>
 11 <#macro classQualifiedName>${basepackage}.model.${className}</#macro>
 12 <#macro exampleQualifiedName>${basepackage}.model.${className}Example</#macro>
 13 <mapper namespace="<@namespace/>">
 14 
 15     <resultMap id="BaseResultMap" type="<@classQualifiedName/>">
 16         <#list table.columns as column>
 17         <#if column.isPk() >
 18         <id property="${column.columnNameLower}" jdbcType="${column.jdbcType}" column="${column.sqlName}"/>
 19         <#else>
 20         <result property="${column.columnNameLower}" jdbcType="${column.jdbcType}" column="${column.sqlName}"/>
 21         </#if>
 22         </#list>
 23     </resultMap>
 24     
 25     <sql id="Base_Column_List">
 26     <#list table.columns as column>
 27         ${column.sqlName}<#if column_has_next>,</#if>
 28     </#list>
 29     </sql>
 30     
 31     <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
 32     <insert id="insert" parameterType="<@classQualifiedName/>" >
 33         <selectKey keyProperty="${table.idColumn.columnNameFirstLower}" order="AFTER" resultType="${table.idColumn.javaType}">
 34             SELECT LAST_INSERT_ID()
 35            </selectKey>
 36         INSERT INTO ${table.sqlName} (
 37         <#list table.notPkColumns as column>
 38             ${column.sqlName}<#if column_has_next>,</#if>
 39         </#list>
 40         ) VALUES (
 41         <#list table.notPkColumns as column>
 42             <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 43         </#list>        
 44         )
 45     </insert>
 46     
 47     <insert id="insertSelective" parameterType="<@classQualifiedName/>" >
 48            <selectKey keyProperty="${table.idColumn.columnNameFirstLower}" order="AFTER" resultType="${table.idColumn.javaType}">
 49             SELECT LAST_INSERT_ID()
 50         </selectKey>
 51            INSERT INTO ${table.sqlName} 
 52            <trim prefix="(" suffix=")" suffixOverrides=",">
 53         <#list table.notPkColumns as column>
 54             <if test="${column.columnNameFirstLower} != null">
 55                 ${column.sqlName},
 56             </if>
 57         </#list>
 58         </trim>  
 59         <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
 60            <#list table.notPkColumns as column>
 61                <if test="${column.columnNameFirstLower} != null">
 62                    <@mapperElP column.columnNameFirstLower column.jdbcType/>,
 63                </if>
 64         </#list> 
 65         </trim>
 66     </insert>
 67     
 68     <update id="updateByPrimaryKey" >
 69         UPDATE ${table.sqlName} SET
 70             <#list table.notPkColumns as column>
 71             ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 72             </#list>
 73         WHERE 
 74             <#list table.compositeIdColumns as column>
 75             ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 76             </#list>            
 77     </update>
 78     
 79     <update id="updateByPrimaryKeySelective" >
 80         UPDATE ${table.sqlName} SET
 81             <#list table.notPkColumns as column>
 82             <if test="${column.columnNameFirstLower} != null">
 83                 ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 84             </if>
 85             </#list>
 86         WHERE 
 87             <#list table.compositeIdColumns as column>
 88             ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 89             </#list>            
 90     </update>
 91 
 92     <delete id="deleteByPrimaryKey">
 93         DELETE FROM ${table.sqlName} WHERE
 94         <#list table.compositeIdColumns as column>
 95         ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
 96         </#list>
 97     </delete>
 98     
 99     <select id="selectByPrimaryKey" resultMap="BaseResultMap">
100         SELECT <include refid="Base_Column_List" />
101         FROM ${table.sqlName}
102         WHERE 
103             <#list table.compositeIdColumns as column>
104             ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
105             </#list>    
106     </select>
107     
108     <sql id="Example_Where_Clause">
109       <where>
110         <foreach collection="oredCriteria" item="criteria" separator="or">
111           <if test="criteria.valid">
112             <trim prefix="(" prefixOverrides="and" suffix=")">
113               <foreach collection="criteria.criteria" item="criterion">
114                 <choose>
115                     <when test="criterion.noValue">
116                         and <@mapperElJ 'criterion.condition' />
117                     </when>
118                     <when test="criterion.singleValue">
119                         and <@mapperElJ 'criterion.condition' /> <@mapperEl 'criterion.value' />
120                     </when>
121                     <when test="criterion.betweenValue">
122                         and <@mapperElJ "criterion.condition" /> <@mapperEl 'criterion.value' /> and <@mapperEl 'criterion.secondValue' />
123                     </when>
124                     <when test="criterion.listValue">
125                         and <@mapperElJ 'criterion.condition' />
126                         <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","><@mapperEl 'listItem' /></foreach>
127                     </when>
128                 </choose>
129               </foreach>
130             </trim>
131           </if>
132         </foreach>
133       </where>
134     </sql>    
135 
136     <sql id="Update_By_Example_Where_Clause">
137         <where>
138             <foreach collection="example.oredCriteria" item="criteria"
139                 separator="or">
140                 <if test="criteria.valid">
141                     <trim prefix="(" prefixOverrides="and" suffix=")">
142                         <foreach collection="criteria.criteria" item="criterion">
143                             <choose>
144                                 <when test="criterion.noValue">
145                                     and <@mapperElJ 'criterion.condition' />
146                                 </when>
147                                 <when test="criterion.singleValue">
148                                     and <@mapperElJ 'criterion.condition' /> <@mapperEl 'criterion.value' />
149                                 </when>
150                                 <when test="criterion.betweenValue">
151                                     and <@mapperElJ "criterion.condition" /> <@mapperEl 'criterion.value' /> and <@mapperEl 'criterion.secondValue' />
152                                 </when>
153                                 <when test="criterion.listValue">
154                                     and <@mapperElJ 'criterion.condition' />
155                                     <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","><@mapperEl 'listItem' /></foreach>
156                                 </when>
157                             </choose>
158                         </foreach>
159                     </trim>
160                 </if>
161             </foreach>
162         </where>
163     </sql>
164     
165     <update id="updateByExample" parameterType="map">
166         UPDATE ${table.sqlName} SET
167             <#list table.columns as column>
168             ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
169             </#list>
170         <if test="_parameter != null">
171             <include refid="Update_By_Example_Where_Clause" />
172         </if>
173     </update>
174     
175     <update id="updateByExampleSelective" parameterType="map">
176         UPDATE ${table.sqlName} SET
177             <#list table.columns as column>
178             <if test="${column.columnNameFirstLower} != null">
179                 ${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
180             </if>
181             </#list>
182         <if test="_parameter != null">
183             <include refid="Update_By_Example_Where_Clause" />
184         </if>
185     </update>
186     
187     <delete id="deleteByExample" parameterType="<@exampleQualifiedName/>">
188         delete from ${table.sqlName}
189         <if test="_parameter != null">
190             <include refid="Example_Where_Clause" />
191         </if>
192     </delete>
193     
194     <select id="countByExample" parameterType="<@exampleQualifiedName/>" resultType="java.lang.Long">
195         select count(*) from ${table.sqlName}
196         <if test="_parameter != null">
197             <include refid="Example_Where_Clause" />
198         </if>
199     </select>
200     
201     <select id="selectByExample" parameterType="<@exampleQualifiedName/>" resultMap="BaseResultMap">
202         select
203         <if test="distinct">
204             distinct
205         </if>
206         <include refid="Base_Column_List" />
207         from ${table.sqlName}
208         <if test="_parameter != null">
209             <include refid="Example_Where_Clause" />
210         </if>
211         <if test="orderByClause != null">
212             order by <@mapperElJ 'orderByClause' />
213         </if>
214     </select>
215     
216 </mapper>

   e、${className}Mapper-Manual.xml

 1 <#include "/macro.include"/>
 2 <#assign className = table.className>   
 3 <#assign classNameFirstLower = table.classNameFirstLower>   
 4 <?xml version="1.0" encoding="UTF-8" ?>
 5 <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
 6 
 7 <#macro namespace>${basepackage}.dao.${className}Dao</#macro>
 8 <!-- 存放手写的sql -->
 9 <mapper namespace="<@namespace/>">
10     
11 </mapper>
View Code

   f、custom.include

1 <#-- 本文件包含一些公共的变量 -->
2 
3 <#-- actionBasePath 用于struts,springmvc框架的action路径前缀,如 /namespace/User/list.do的/namespace/User部分,可以自定义这个变量 -->
4 <#assign actionBasePath = "/"+namespace+"/"+table.className>
5 
6 <#-- jspFileBasePath 用于struts,springmvc框架的java文件引用的jsp前缀,如 /namespace/User/list.jsp的/namespace/User部分 -->
7 <#assign jspFileBasePath = "/"+namespace+"/"+table.className>
View Code

   g、java_copyright.include

1 /**
2  * 版权相关
3  */
View Code

   h、java_imports.include,公共导入类

   i、macro.include

 1 <#-- 本文件包含一些公共的函数,本文件会被其它模板自动include -->
 2 
 3 <#-- 将value变成jsp el表达式,主要由于FreeMarker生成表达式不方便 -->
 4 <#macro jspEl value>${r"${"}${value}}</#macro>
 5 
 6 <#-- 生成java构造函数 -->
 7 <#macro generateConstructor constructor>
 8     public ${constructor}(){
 9     }
10 
11     public ${constructor}(
12     <#list table.compositeIdColumns as column>
13         ${column.javaType} ${column.columnNameLower}<#if column_has_next>,</#if>
14     </#list>        
15     ){
16     <#list table.compositeIdColumns as column>
17         <#if column.pk>
18         this.${column.columnNameLower} = ${column.columnNameLower};
19         </#if>
20     </#list>    
21     }
22 
23 </#macro>
View Code

  6、编辑方法运行代码

 1 package com.test.rapid.generator;
 2 
 3 import cn.org.rapid_framework.generator.GeneratorFacade;
 4 
 5 /**
 6  * 
 7  * @author H__D
 8  * @date 2019-07-31 22:27:05
 9  *
10  */
11 
12 public class CodeGenerator {
13 
14     public static void main(String[] args) throws Exception {
15 
16         // 模板地址
17         String templatePath = "classpath:template";
18         GeneratorFacade g = new GeneratorFacade();
19         g.getGenerator().addTemplateRootDir(templatePath);
20         // 删除生成器的输出目录//
21         g.deleteOutRootDir();
22         // 通过数据库表生成文件
23         g.generateByTable("god_user");
24         
25         // 自动搜索数据库中的所有表并生成文件,template为模板的根目录
26         // g.generateByAllTable();
27         // 按table名字删除文件
28         // g.deleteByTable("table_name", "template");
29         //打开文件夹
30         //Runtime.getRuntime().exec("cmd.exe /c start "+GeneratorProperties.getRequiredProperty("outRoot"));
31     }
32 
33 }

  7、生成代码如下:

    a、dao

 1 /**
 2  * 版权相关
 3  */
 4 package com.test.dao;
 5 
 6 
 7 import java.util.List;
 8 import org.apache.ibatis.annotations.Param;
 9 
10 import com.test.model.GodUser;
11 import com.test.model.GodUserExample;
12 
13 
14 /**
15  * 用户表 DAO层
16  * 
17  * @author God
18  * @date 2019-08-02 00:44:02
19  */
20 public interface GodUserDao {
21     
22     /**
23      * 统计记录-根据示例条件
24      */
25     long countByExample(GodUserExample example);
26 
27     /**
28      * 删除记录-根据示例条件
29      */
30     int deleteByExample(GodUserExample example);
31 
32     /**
33      * 删除记录-根据主键
34      */
35     int deleteByPrimaryKey(Integer id);
36 
37     /**
38      * 插入记录-完全插入
39      */
40     int insert(GodUser record);
41 
42     /**
43      * 插入记录-选择性插入
44      */
45     int insertSelective(GodUser record);
46 
47     /**
48      * 查询记录-根据示例条件
49      */
50     List<GodUser> selectByExample(GodUserExample example);
51 
52     /**
53      * 查询记录-根据主键
54      */
55     GodUser selectByPrimaryKey(Integer id);
56 
57     /**
58      * 更新记录-根据示例条件选择性更新
59      */
60     int updateByExampleSelective(@Param("record") GodUser record, @Param("example") GodUserExample example);
61 
62     /**
63      * 更新记录-根据示例条件更新
64      */
65     int updateByExample(@Param("record") GodUser record, @Param("example") GodUserExample example);
66 
67     /**
68      * 更新记录-根据主键选择性更新
69      * @return
70      */
71     int updateByPrimaryKeySelective(GodUser record);
72 
73     /**
74      * 更新记录-根据主键更新
75      * @return
76      */
77     int updateByPrimaryKey(GodUser record);
78     
79 }
View Code

    b、model

  1 /**
  2  * 版权相关
  3  */
  4 package com.test.model;
  5 
  6 import java.io.Serializable;
  7 import java.util.Date;
  8 
  9 
 10 /**
 11  * 用户表 实体类
 12  * 
 13  * @author God
 14  * @date 2019-08-02 00:44:02
 15  */
 16 public class GodUser implements java.io.Serializable{
 17     
 18     private static final long serialVersionUID = 1L;    
 19     
 20     /**
 21      * ID 
 22      */
 23     private Integer id;
 24     /**
 25      * 名称 
 26      */
 27     private String name;
 28     /**
 29      * 密码 
 30      */
 31     private String password;
 32     /**
 33      * 昵称 
 34      */
 35     private String nickname;
 36     /**
 37      * 状态 0禁用 1启用 
 38      */
 39     private Integer status;
 40     /**
 41      * 创建时间 
 42      */
 43     private Date createTime;
 44     /**
 45      * 修改时间 
 46      */
 47     private Date updateTime;
 48     
 49         
 50     public void setId(Integer value) {
 51         this.id = value;
 52     }
 53     
 54     public Integer getId() {
 55         return this.id;
 56     }
 57         
 58     public void setName(String value) {
 59         this.name = value;
 60     }
 61     
 62     public String getName() {
 63         return this.name;
 64     }
 65         
 66     public void setPassword(String value) {
 67         this.password = value;
 68     }
 69     
 70     public String getPassword() {
 71         return this.password;
 72     }
 73         
 74     public void setNickname(String value) {
 75         this.nickname = value;
 76     }
 77     
 78     public String getNickname() {
 79         return this.nickname;
 80     }
 81         
 82     public void setStatus(Integer value) {
 83         this.status = value;
 84     }
 85     
 86     public Integer getStatus() {
 87         return this.status;
 88     }
 89         
 90     public void setCreateTime(Date value) {
 91         this.createTime = value;
 92     }
 93     
 94     public Date getCreateTime() {
 95         return this.createTime;
 96     }
 97         
 98     public void setUpdateTime(Date value) {
 99         this.updateTime = value;
100     }
101     
102     public Date getUpdateTime() {
103         return this.updateTime;
104     }
105 
106 }
View Code

    c、mapper.xml

  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
  3 
  4 <mapper namespace="com.test.dao.GodUserDao">
  5 
  6     <resultMap id="BaseResultMap" type="com.test.model.GodUser">
  7         <id property="id" jdbcType="INTEGER" column="id"/>
  8         <result property="name" jdbcType="VARCHAR" column="name"/>
  9         <result property="password" jdbcType="VARCHAR" column="password"/>
 10         <result property="nickname" jdbcType="VARCHAR" column="nickname"/>
 11         <result property="status" jdbcType="INTEGER" column="status"/>
 12         <result property="createTime" jdbcType="TIMESTAMP" column="create_time"/>
 13         <result property="updateTime" jdbcType="TIMESTAMP" column="update_time"/>
 14     </resultMap>
 15     
 16     <sql id="Base_Column_List">
 17         id,
 18         name,
 19         password,
 20         nickname,
 21         status,
 22         create_time,
 23         update_time
 24     </sql>
 25     
 26     <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
 27     <insert id="insert" parameterType="com.test.model.GodUser" >
 28         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
 29             SELECT LAST_INSERT_ID()
 30            </selectKey>
 31         INSERT INTO god_user (
 32             name,
 33             password,
 34             nickname,
 35             status,
 36             create_time,
 37             update_time
 38         ) VALUES (
 39             #{name,jdbcType=VARCHAR},
 40             #{password,jdbcType=VARCHAR},
 41             #{nickname,jdbcType=VARCHAR},
 42             #{status,jdbcType=INTEGER},
 43             #{createTime,jdbcType=TIMESTAMP},
 44             #{updateTime,jdbcType=TIMESTAMP}
 45         )
 46     </insert>
 47     
 48     <insert id="insertSelective" parameterType="com.test.model.GodUser" >
 49            <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
 50             SELECT LAST_INSERT_ID()
 51         </selectKey>
 52            INSERT INTO god_user 
 53            <trim prefix="(" suffix=")" suffixOverrides=",">
 54             <if test="name != null">
 55                 name,
 56             </if>
 57             <if test="password != null">
 58                 password,
 59             </if>
 60             <if test="nickname != null">
 61                 nickname,
 62             </if>
 63             <if test="status != null">
 64                 status,
 65             </if>
 66             <if test="createTime != null">
 67                 create_time,
 68             </if>
 69             <if test="updateTime != null">
 70                 update_time,
 71             </if>
 72         </trim>  
 73         <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
 74                <if test="name != null">
 75                    #{name,jdbcType=VARCHAR},
 76                </if>
 77                <if test="password != null">
 78                    #{password,jdbcType=VARCHAR},
 79                </if>
 80                <if test="nickname != null">
 81                    #{nickname,jdbcType=VARCHAR},
 82                </if>
 83                <if test="status != null">
 84                    #{status,jdbcType=INTEGER},
 85                </if>
 86                <if test="createTime != null">
 87                    #{createTime,jdbcType=TIMESTAMP},
 88                </if>
 89                <if test="updateTime != null">
 90                    #{updateTime,jdbcType=TIMESTAMP},
 91                </if>
 92         </trim>
 93     </insert>
 94     
 95     <update id="updateByPrimaryKey" >
 96         UPDATE god_user SET
 97             name = #{name,jdbcType=VARCHAR},
 98             password = #{password,jdbcType=VARCHAR},
 99             nickname = #{nickname,jdbcType=VARCHAR},
100             status = #{status,jdbcType=INTEGER},
101             create_time = #{createTime,jdbcType=TIMESTAMP},
102             update_time = #{updateTime,jdbcType=TIMESTAMP}
103         WHERE 
104             id = #{id,jdbcType=INTEGER}
105     </update>
106     
107     <update id="updateByPrimaryKeySelective" >
108         UPDATE god_user SET
109             <if test="name != null">
110                 name = #{name,jdbcType=VARCHAR},
111             </if>
112             <if test="password != null">
113                 password = #{password,jdbcType=VARCHAR},
114             </if>
115             <if test="nickname != null">
116                 nickname = #{nickname,jdbcType=VARCHAR},
117             </if>
118             <if test="status != null">
119                 status = #{status,jdbcType=INTEGER},
120             </if>
121             <if test="createTime != null">
122                 create_time = #{createTime,jdbcType=TIMESTAMP},
123             </if>
124             <if test="updateTime != null">
125                 update_time = #{updateTime,jdbcType=TIMESTAMP}
126             </if>
127         WHERE 
128             id = #{id,jdbcType=INTEGER}
129     </update>
130 
131     <delete id="deleteByPrimaryKey">
132         DELETE FROM god_user WHERE
133         id = #{id,jdbcType=INTEGER}
134     </delete>
135     
136     <select id="selectByPrimaryKey" resultMap="BaseResultMap">
137         SELECT <include refid="Base_Column_List" />
138         FROM god_user
139         WHERE 
140             id = #{id,jdbcType=INTEGER}
141     </select>
142     
143     <sql id="Example_Where_Clause">
144       <where>
145         <foreach collection="oredCriteria" item="criteria" separator="or">
146           <if test="criteria.valid">
147             <trim prefix="(" prefixOverrides="and" suffix=")">
148               <foreach collection="criteria.criteria" item="criterion">
149                 <choose>
150                     <when test="criterion.noValue">
151                         and ${criterion.condition}
152                     </when>
153                     <when test="criterion.singleValue">
154                         and ${criterion.condition} #{criterion.value}
155                     </when>
156                     <when test="criterion.betweenValue">
157                         and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
158                     </when>
159                     <when test="criterion.listValue">
160                         and ${criterion.condition}
161                         <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach>
162                     </when>
163                 </choose>
164               </foreach>
165             </trim>
166           </if>
167         </foreach>
168       </where>
169     </sql>    
170 
171     <sql id="Update_By_Example_Where_Clause">
172         <where>
173             <foreach collection="example.oredCriteria" item="criteria"
174                 separator="or">
175                 <if test="criteria.valid">
176                     <trim prefix="(" prefixOverrides="and" suffix=")">
177                         <foreach collection="criteria.criteria" item="criterion">
178                             <choose>
179                                 <when test="criterion.noValue">
180                                     and ${criterion.condition}
181                                 </when>
182                                 <when test="criterion.singleValue">
183                                     and ${criterion.condition} #{criterion.value}
184                                 </when>
185                                 <when test="criterion.betweenValue">
186                                     and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
187                                 </when>
188                                 <when test="criterion.listValue">
189                                     and ${criterion.condition}
190                                     <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach>
191                                 </when>
192                             </choose>
193                         </foreach>
194                     </trim>
195                 </if>
196             </foreach>
197         </where>
198     </sql>
199     
200     <update id="updateByExample" parameterType="map">
201         UPDATE god_user SET
202             id = #{id,jdbcType=INTEGER},
203             name = #{name,jdbcType=VARCHAR},
204             password = #{password,jdbcType=VARCHAR},
205             nickname = #{nickname,jdbcType=VARCHAR},
206             status = #{status,jdbcType=INTEGER},
207             create_time = #{createTime,jdbcType=TIMESTAMP},
208             update_time = #{updateTime,jdbcType=TIMESTAMP}
209         <if test="_parameter != null">
210             <include refid="Update_By_Example_Where_Clause" />
211         </if>
212     </update>
213     
214     <update id="updateByExampleSelective" parameterType="map">
215         UPDATE god_user SET
216             <if test="id != null">
217                 id = #{id,jdbcType=INTEGER},
218             </if>
219             <if test="name != null">
220                 name = #{name,jdbcType=VARCHAR},
221             </if>
222             <if test="password != null">
223                 password = #{password,jdbcType=VARCHAR},
224             </if>
225             <if test="nickname != null">
226                 nickname = #{nickname,jdbcType=VARCHAR},
227             </if>
228             <if test="status != null">
229                 status = #{status,jdbcType=INTEGER},
230             </if>
231             <if test="createTime != null">
232                 create_time = #{createTime,jdbcType=TIMESTAMP},
233             </if>
234             <if test="updateTime != null">
235                 update_time = #{updateTime,jdbcType=TIMESTAMP}
236             </if>
237         <if test="_parameter != null">
238             <include refid="Update_By_Example_Where_Clause" />
239         </if>
240     </update>
241     
242     <delete id="deleteByExample" parameterType="com.test.model.GodUserExample">
243         delete from god_user
244         <if test="_parameter != null">
245             <include refid="Example_Where_Clause" />
246         </if>
247     </delete>
248     
249     <select id="countByExample" parameterType="com.test.model.GodUserExample" resultType="java.lang.Long">
250         select count(*) from god_user
251         <if test="_parameter != null">
252             <include refid="Example_Where_Clause" />
253         </if>
254     </select>
255     
256     <select id="selectByExample" parameterType="com.test.model.GodUserExample" resultMap="BaseResultMap">
257         select
258         <if test="distinct">
259             distinct
260         </if>
261         <include refid="Base_Column_List" />
262         from god_user
263         <if test="_parameter != null">
264             <include refid="Example_Where_Clause" />
265         </if>
266         <if test="orderByClause != null">
267             order by #{orderByClause}
268         </if>
269     </select>
270     
271 </mapper>
View Code

   

  

原文地址:https://www.cnblogs.com/h--d/p/11286258.html