【Java】 rapid-generator 代码生成器
rapid-generator是一个生成器引擎,让你可以专注与代码生成器模板的编写, 可以生成如ibatis,ibatis3,hibernate,spring_mvc,struts2等等代码.
rapid-generator是设置Freemarker模版,JDBC获取数据库信息,将数据库信息和模版绑定,输出代码文件
rapid-generator 使用
1、新建一个Maven项目
2、引入rapid-generator相关依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test-rapid-generator</artifactId>
<version>0.0.1-SNAPSHOT</version> <dependencies>
<!-- 代码生成工具 -->
<dependency>
<groupId>com.googlecode.rapid-framework</groupId>
<artifactId>rapid-generator</artifactId>
<version>4.0.6</version>
</dependency> <!-- mysql数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency> <!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.2.135</version>
</dependency> <!-- 代码生成器扩展包 -->
<dependency>
<groupId>com.googlecode.rapid-framework</groupId>
<artifactId>rapid-generator-ext</artifactId>
<version>4.0.6</version>
</dependency> <!-- 代码生成器模板,模板根目录通过 classpath:generator/template/rapid 可以引用 -->
<dependency>
<groupId>com.googlecode.rapid-framework</groupId>
<artifactId>rapid-generator-template</artifactId>
<version>4.0.6</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3、增加log4j.properties配置文件
### 设置###
log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
4、增加generator.xml配置文件,配置代码生成器相关属性
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>
代码生成器配置文件:
1.会为所有的property生成property_dir属性,如pkg=com.company => pkg_dir=com/company
2.可以引用环境变量: ${env.JAVA_HOME} or System.properties: ${user.home},property之间也可以相互引用
</comment> <entry key="author">God</entry> <entry key="basepackage">com.test</entry> <!-- jsp namespace: web/${namespace}/${className}/list.jsp -->
<entry key="namespace">pages</entry> <!-- 对应修改下Constants.Mybatis.NAMESPACE_PREFIX -->
<entry key="namespace_prefix">com.test.model</entry> <entry key="outRoot">/Users/H__D/Desktop/generator-output</entry> <!-- 需要移除的表名前缀,使用逗号进行分隔多个前缀,示例值: t_,v_ -->
<entry key="tableRemovePrefixes"></entry> <entry key="jdbc_username">admin</entry>
<entry key="jdbc_password">admin</entry> <!-- oracle需要指定jdbc.schema,其它数据库忽略此项配置 -->
<entry key="jdbc_schema"></entry>
<entry key="jdbc_catalog"></entry> <!-- 数据库类型映射 -->
<entry key="java_typemapping.java.sql.Timestamp">java.util.Date</entry>
<entry key="java_typemapping.java.sql.Date">java.util.Date</entry>
<entry key="java_typemapping.java.sql.Time">java.util.Date</entry>
<entry key="java_typemapping.java.lang.Byte">Integer</entry>
<entry key="java_typemapping.java.lang.Short">Integer</entry>
<entry key="java_typemapping.java.math.BigDecimal">Long</entry> <!-- H2 -->
<!-- <entry key="jdbc.url">jdbc:h2:tcp://localhost/test</entry>
<entry key="jdbc.driver">org.h2.Driver</entry>
--> <entry key="jdbc_url">jdbc:mysql://127.0.0.1/god?allowPublicKeyRetrieval=true</entry>
<entry key="jdbc_driver">com.mysql.jdbc.Driver</entry> <!-- Oracle jdbc:oracle:oci:@tnsname_devdb
<entry key="jdbc.url">jdbc:oracle:thin:@192.168.0.177:1521:[sid]</entry>
<entry key="jdbc.driver">oracle.jdbc.driver.OracleDriver</entry>
--> <!-- SQLServer2000
<entry key="jdbc.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=[database]</entry>
<entry key="jdbc.driver">com.microsoft.jdbc.sqlserver.SQLServerDriver</entry>
--> <!-- SQLServer2005
<entry key="jdbc.url">jdbc:sqlserver://192.168.0.98:1433;DatabaseName=[database]</entry>
<entry key="jdbc.driver">com.microsoft.sqlserver.jdbc.SQLServerDriver</entry>
--> <!-- JTDs for SQLServer
<entry key="jdbc.url">jdbc:jtds:sqlserver://192.168.0.102:1433/[database];tds=8.0;lastupdatecount=true</entry>
<entry key="jdbc.driver">net.sourceforge.jtds.jdbc.Driver</entry>
--> <!-- PostgreSql
<entry key="jdbc.url">jdbc:postgresql://localhost/[database]</entry>
<entry key="jdbc.driver">org.postgresql.Driver</entry>
--> <!-- Sybase
<entry key="jdbc.url">jdbc:sybase:Tds:localhost:5007/[database]</entry>
<entry key="jdbc.driver">com.sybase.jdbc.SybDriver</entry>
--> <!-- DB2
<entry key="jdbc.url">jdbc:db2://localhost:5000/[database]</entry>
<entry key="jdbc.driver">com.ibm.db2.jdbc.app.DB2Driver</entry>
--> <!-- HsqlDB
<entry key="jdbc.url">jdbc:hsqldb:mem:generatorDB</entry>
<entry key="jdbc.driver">org.hsqldb.jdbcDriver</entry>
--> <!-- Derby
<entry key="jdbc.url">jdbc:derby://localhost/databaseName</entry>
<entry key="jdbc.driver">org.apache.derby.jdbc.ClientDriver</entry>
--> </properties>
5、配置代码模版文件
a、${className}Dao.java
<#include "/java_copyright.include">
<#assign className = table.className>
<#assign classNameLower = className?uncap_first>
package ${basepackage}.dao; <#include "/java_imports.include"> import java.util.List;
import org.apache.ibatis.annotations.Param; import ${basepackage}.model.${className};
import ${basepackage}.model.${className}Example; /**
* ${table.remarks } DAO层
*
* @author ${author}
* @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
*/
public interface ${className}Dao { /**
* 统计记录-根据示例条件
*/
long countByExample(${className}Example example); /**
* 删除记录-根据示例条件
*/
int deleteByExample(${className}Example example); /**
* 删除记录-根据主键
*/
int deleteByPrimaryKey(Integer id); /**
* 插入记录-完全插入
*/
int insert(${className} record); /**
* 插入记录-选择性插入
*/
int insertSelective(${className} record); /**
* 查询记录-根据示例条件
*/
List<${className}> selectByExample(${className}Example example); /**
* 查询记录-根据主键
*/
${className} selectByPrimaryKey(Integer id); /**
* 更新记录-根据示例条件选择性更新
*/
int updateByExampleSelective(@Param("record") ${className} record, @Param("example") ${className}Example example); /**
* 更新记录-根据示例条件更新
*/
int updateByExample(@Param("record") ${className} record, @Param("example") ${className}Example example); /**
* 更新记录-根据主键选择性更新
* @return
*/
int updateByPrimaryKeySelective(${className} record); /**
* 更新记录-根据主键更新
* @return
*/
int updateByPrimaryKey(${className} record); }
b、${className}.java
<#include "/macro.include"/>
<#include "/java_copyright.include">
<#assign className = table.className>
<#assign classNameLower = className?uncap_first>
<#assign hasDateType = false>
package ${basepackage}.model; <#list table.columns as column>
<#if column.isDateTimeColumn>
<#assign hasDateType = true>
</#if>
</#list>
import java.io.Serializable;
<#if hasDateType>
import java.util.Date;
</#if> <#include "/java_imports.include"> /**
* ${table.remarks } 实体类
*
* @author ${author}
* @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
*/
public class ${className} implements java.io.Serializable{ private static final long serialVersionUID = 1L; <#list table.columns as column>
/**
* ${column.columnAlias!}
*/
private ${column.simpleJavaType} ${column.columnNameLower};
</#list> <@generateJavaColumns/> } <#macro generateJavaColumns>
<#list table.columns as column> public void set${column.columnName}(${column.simpleJavaType} value) {
this.${column.columnNameLower} = value;
} public ${column.simpleJavaType} get${column.columnName}() {
return this.${column.columnNameLower};
}
</#list>
</#macro>
c、${className}Example.java
<#include "/macro.include"/>
<#include "/java_copyright.include">
<#assign className = table.className>
<#assign classNameLower = className?uncap_first>
<#assign hasDateType = false>
package ${querypackage}; <#list table.columns as column>
<#if column.isDateTimeColumn>
<#assign hasDateType = true>
</#if>
</#list>
import java.io.Serializable;
<#if hasDateType>
import java.util.Date;
</#if>
import java.util.ArrayList;
import java.util.List; <#include "/java_imports.include"> /**
* ${table.remarks } 示例类
*
* @author ${author}
* @date ${.now?string('yyyy-MM-dd HH:mm:ss')}
*/
public class ${className}Example implements java.io.Serializable{ private static final long serialVersionUID = 1L; protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ${className}Example() {
oredCriteria = new ArrayList<Criteria>();
} public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
} public String getOrderByClause() {
return orderByClause;
} public void setDistinct(boolean distinct) {
this.distinct = distinct;
} public boolean isDistinct() {
return distinct;
} public List<Criteria> getOredCriteria() {
return oredCriteria;
} public void or(Criteria criteria) {
oredCriteria.add(criteria);
} public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
} public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
} protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
} public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
} protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria; protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
} public boolean isValid() {
return criteria.size() > 0;
} public List<Criterion> getAllCriteria() {
return criteria;
} public List<Criterion> getCriteria() {
return criteria;
} protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
} protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
} protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
} <#list table.columns as column>
public Criteria and${column.columnName}IsNull() {
addCriterion("${column.sqlName} is null");
return (Criteria) this;
}
public Criteria and${column.columnName}IsNotNull() {
addCriterion("${column.sqlName} is not null");
return (Criteria) this;
}
public Criteria and${column.columnName}EqualTo(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} =", value, "${column.columnNameLower}");
return (Criteria) this;
}
public Criteria and${column.columnName}NotEqualTo(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} <>", value, "${column.columnNameLower}");
return (Criteria) this;
}
public Criteria and${column.columnName}GreaterThan(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} >", value, "${column.columnNameLower}");
return (Criteria) this;
}
public Criteria and${column.columnName}GreaterThanOrEqualTo(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} >=", value, "${column.columnNameLower}");
return (Criteria) this;
}
public Criteria and${column.columnName}LessThan(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} <", value, "${column.columnNameLower}");
return (Criteria) this;
} public Criteria and${column.columnName}LessThanOrEqualTo(${column.simpleJavaType} value) {
addCriterion("${column.sqlName} <=", value, "${column.columnNameLower}");
return (Criteria) this;
} <#if column.isStringColumn>
public Criteria and${column.columnName}Like(String value) {
addCriterion("${column.sqlName} like", value, "${column.columnNameLower}");
return (Criteria) this;
} public Criteria and${column.columnName}NotLike(String value) {
addCriterion("${column.sqlName} not like", value, "${column.columnNameLower}");
return (Criteria) this;
} </#if>
public Criteria and${column.columnName}In(List<${column.simpleJavaType}> values) {
addCriterion("${column.sqlName} in", values, "${column.columnNameLower}");
return (Criteria) this;
} public Criteria and${column.columnName}NotIn(List<${column.simpleJavaType}> values) {
addCriterion("${column.sqlName} not in", values, "${column.columnNameLower}");
return (Criteria) this;
} public Criteria and${column.columnName}Between(${column.simpleJavaType} value1, ${column.simpleJavaType} value2) {
addCriterion("${column.sqlName} between", value1, value2, "${column.columnNameLower}");
return (Criteria) this;
} public Criteria and${column.columnName}NotBetween(${column.simpleJavaType} value1, ${column.simpleJavaType} value2) {
addCriterion("${column.sqlName} not between", value1, value2, "${column.columnNameLower}");
return (Criteria) this;
}
</#list>
} public static class Criteria extends GeneratedCriteria { protected Criteria() {
super();
}
} public static class Criterion {
private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() {
return condition;
} public Object getValue() {
return value;
} public Object getSecondValue() {
return secondValue;
} public boolean isNoValue() {
return noValue;
} public boolean isSingleValue() {
return singleValue;
} public boolean isBetweenValue() {
return betweenValue;
} public boolean isListValue() {
return listValue;
} public String getTypeHandler() {
return typeHandler;
} protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
} protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
} protected Criterion(String condition, Object value) {
this(condition, value, null);
} protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
} protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
d、${className}Mapper.xml
<#include "/macro.include"/>
<#assign className = table.className>
<#assign classNameFirstLower = table.classNameFirstLower>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <#macro mapperEl value>${r"#{"}${value}}</#macro>
<#macro mapperElJ value>${r"${"}${value}}</#macro>
<#macro mapperElP value jdbcType>${r"#{"}${value},jdbcType=${jdbcType}}</#macro>
<#macro namespace>${basepackage}.dao.${className}Dao</#macro>
<#macro classQualifiedName>${basepackage}.model.${className}</#macro>
<#macro exampleQualifiedName>${basepackage}.model.${className}Example</#macro>
<mapper namespace="<@namespace/>"> <resultMap id="BaseResultMap" type="<@classQualifiedName/>">
<#list table.columns as column>
<#if column.isPk() >
<id property="${column.columnNameLower}" jdbcType="${column.jdbcType}" column="${column.sqlName}"/>
<#else>
<result property="${column.columnNameLower}" jdbcType="${column.jdbcType}" column="${column.sqlName}"/>
</#if>
</#list>
</resultMap> <sql id="Base_Column_List">
<#list table.columns as column>
${column.sqlName}<#if column_has_next>,</#if>
</#list>
</sql> <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
<insert id="insert" parameterType="<@classQualifiedName/>" >
<selectKey keyProperty="${table.idColumn.columnNameFirstLower}" order="AFTER" resultType="${table.idColumn.javaType}">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO ${table.sqlName} (
<#list table.notPkColumns as column>
${column.sqlName}<#if column_has_next>,</#if>
</#list>
) VALUES (
<#list table.notPkColumns as column>
<@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
)
</insert> <insert id="insertSelective" parameterType="<@classQualifiedName/>" >
<selectKey keyProperty="${table.idColumn.columnNameFirstLower}" order="AFTER" resultType="${table.idColumn.javaType}">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO ${table.sqlName}
<trim prefix="(" suffix=")" suffixOverrides=",">
<#list table.notPkColumns as column>
<if test="${column.columnNameFirstLower} != null">
${column.sqlName},
</if>
</#list>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<#list table.notPkColumns as column>
<if test="${column.columnNameFirstLower} != null">
<@mapperElP column.columnNameFirstLower column.jdbcType/>,
</if>
</#list>
</trim>
</insert> <update id="updateByPrimaryKey" >
UPDATE ${table.sqlName} SET
<#list table.notPkColumns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
WHERE
<#list table.compositeIdColumns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
</update> <update id="updateByPrimaryKeySelective" >
UPDATE ${table.sqlName} SET
<#list table.notPkColumns as column>
<if test="${column.columnNameFirstLower} != null">
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</if>
</#list>
WHERE
<#list table.compositeIdColumns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
</update> <delete id="deleteByPrimaryKey">
DELETE FROM ${table.sqlName} WHERE
<#list table.compositeIdColumns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
</delete> <select id="selectByPrimaryKey" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List" />
FROM ${table.sqlName}
WHERE
<#list table.compositeIdColumns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
</select> <sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and <@mapperElJ 'criterion.condition' />
</when>
<when test="criterion.singleValue">
and <@mapperElJ 'criterion.condition' /> <@mapperEl 'criterion.value' />
</when>
<when test="criterion.betweenValue">
and <@mapperElJ "criterion.condition" /> <@mapperEl 'criterion.value' /> and <@mapperEl 'criterion.secondValue' />
</when>
<when test="criterion.listValue">
and <@mapperElJ 'criterion.condition' />
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","><@mapperEl 'listItem' /></foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql> <sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria"
separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and <@mapperElJ 'criterion.condition' />
</when>
<when test="criterion.singleValue">
and <@mapperElJ 'criterion.condition' /> <@mapperEl 'criterion.value' />
</when>
<when test="criterion.betweenValue">
and <@mapperElJ "criterion.condition" /> <@mapperEl 'criterion.value' /> and <@mapperEl 'criterion.secondValue' />
</when>
<when test="criterion.listValue">
and <@mapperElJ 'criterion.condition' />
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","><@mapperEl 'listItem' /></foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql> <update id="updateByExample" parameterType="map">
UPDATE ${table.sqlName} SET
<#list table.columns as column>
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</#list>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update> <update id="updateByExampleSelective" parameterType="map">
UPDATE ${table.sqlName} SET
<#list table.columns as column>
<if test="${column.columnNameFirstLower} != null">
${column.sqlName} = <@mapperElP column.columnNameFirstLower column.jdbcType/><#if column_has_next>,</#if>
</if>
</#list>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update> <delete id="deleteByExample" parameterType="<@exampleQualifiedName/>">
delete from ${table.sqlName}
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete> <select id="countByExample" parameterType="<@exampleQualifiedName/>" resultType="java.lang.Long">
select count(*) from ${table.sqlName}
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select> <select id="selectByExample" parameterType="<@exampleQualifiedName/>" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from ${table.sqlName}
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by <@mapperElJ 'orderByClause' />
</if>
</select> </mapper>
e、${className}Mapper-Manual.xml
<#include "/macro.include"/>
<#assign className = table.className>
<#assign classNameFirstLower = table.classNameFirstLower>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <#macro namespace>${basepackage}.dao.${className}Dao</#macro>
<!-- 存放手写的sql -->
<mapper namespace="<@namespace/>"> </mapper>
f、custom.include
<#-- 本文件包含一些公共的变量 --> <#-- actionBasePath 用于struts,springmvc框架的action路径前缀,如 /namespace/User/list.do的/namespace/User部分,可以自定义这个变量 -->
<#assign actionBasePath = "/"+namespace+"/"+table.className> <#-- jspFileBasePath 用于struts,springmvc框架的java文件引用的jsp前缀,如 /namespace/User/list.jsp的/namespace/User部分 -->
<#assign jspFileBasePath = "/"+namespace+"/"+table.className>
g、java_copyright.include
/**
* 版权相关
*/
h、java_imports.include,公共导入类
i、macro.include
<#-- 本文件包含一些公共的函数,本文件会被其它模板自动include --> <#-- 将value变成jsp el表达式,主要由于FreeMarker生成表达式不方便 -->
<#macro jspEl value>${r"${"}${value}}</#macro> <#-- 生成java构造函数 -->
<#macro generateConstructor constructor>
public ${constructor}(){
} public ${constructor}(
<#list table.compositeIdColumns as column>
${column.javaType} ${column.columnNameLower}<#if column_has_next>,</#if>
</#list>
){
<#list table.compositeIdColumns as column>
<#if column.pk>
this.${column.columnNameLower} = ${column.columnNameLower};
</#if>
</#list>
} </#macro>
6、编辑方法运行代码
package com.test.rapid.generator; import cn.org.rapid_framework.generator.GeneratorFacade; /**
*
* @author H__D
* @date 2019-07-31 22:27:05
*
*/ public class CodeGenerator { public static void main(String[] args) throws Exception { // 模板地址
String templatePath = "classpath:template";
GeneratorFacade g = new GeneratorFacade();
g.getGenerator().addTemplateRootDir(templatePath);
// 删除生成器的输出目录//
g.deleteOutRootDir();
// 通过数据库表生成文件
g.generateByTable("god_user"); // 自动搜索数据库中的所有表并生成文件,template为模板的根目录
// g.generateByAllTable();
// 按table名字删除文件
// g.deleteByTable("table_name", "template");
//打开文件夹
//Runtime.getRuntime().exec("cmd.exe /c start "+GeneratorProperties.getRequiredProperty("outRoot"));
} }
7、生成代码如下:
a、dao
/**
* 版权相关
*/
package com.test.dao; import java.util.List;
import org.apache.ibatis.annotations.Param; import com.test.model.GodUser;
import com.test.model.GodUserExample; /**
* 用户表 DAO层
*
* @author God
* @date 2019-08-02 00:44:02
*/
public interface GodUserDao { /**
* 统计记录-根据示例条件
*/
long countByExample(GodUserExample example); /**
* 删除记录-根据示例条件
*/
int deleteByExample(GodUserExample example); /**
* 删除记录-根据主键
*/
int deleteByPrimaryKey(Integer id); /**
* 插入记录-完全插入
*/
int insert(GodUser record); /**
* 插入记录-选择性插入
*/
int insertSelective(GodUser record); /**
* 查询记录-根据示例条件
*/
List<GodUser> selectByExample(GodUserExample example); /**
* 查询记录-根据主键
*/
GodUser selectByPrimaryKey(Integer id); /**
* 更新记录-根据示例条件选择性更新
*/
int updateByExampleSelective(@Param("record") GodUser record, @Param("example") GodUserExample example); /**
* 更新记录-根据示例条件更新
*/
int updateByExample(@Param("record") GodUser record, @Param("example") GodUserExample example); /**
* 更新记录-根据主键选择性更新
* @return
*/
int updateByPrimaryKeySelective(GodUser record); /**
* 更新记录-根据主键更新
* @return
*/
int updateByPrimaryKey(GodUser record); }
b、model
/**
* 版权相关
*/
package com.test.model; import java.io.Serializable;
import java.util.Date; /**
* 用户表 实体类
*
* @author God
* @date 2019-08-02 00:44:02
*/
public class GodUser implements java.io.Serializable{ private static final long serialVersionUID = 1L; /**
* ID
*/
private Integer id;
/**
* 名称
*/
private String name;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickname;
/**
* 状态 0禁用 1启用
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime; public void setId(Integer value) {
this.id = value;
} public Integer getId() {
return this.id;
} public void setName(String value) {
this.name = value;
} public String getName() {
return this.name;
} public void setPassword(String value) {
this.password = value;
} public String getPassword() {
return this.password;
} public void setNickname(String value) {
this.nickname = value;
} public String getNickname() {
return this.nickname;
} public void setStatus(Integer value) {
this.status = value;
} public Integer getStatus() {
return this.status;
} public void setCreateTime(Date value) {
this.createTime = value;
} public Date getCreateTime() {
return this.createTime;
} public void setUpdateTime(Date value) {
this.updateTime = value;
} public Date getUpdateTime() {
return this.updateTime;
} }
c、mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="com.test.dao.GodUserDao"> <resultMap id="BaseResultMap" type="com.test.model.GodUser">
<id property="id" jdbcType="INTEGER" column="id"/>
<result property="name" jdbcType="VARCHAR" column="name"/>
<result property="password" jdbcType="VARCHAR" column="password"/>
<result property="nickname" jdbcType="VARCHAR" column="nickname"/>
<result property="status" jdbcType="INTEGER" column="status"/>
<result property="createTime" jdbcType="TIMESTAMP" column="create_time"/>
<result property="updateTime" jdbcType="TIMESTAMP" column="update_time"/>
</resultMap> <sql id="Base_Column_List">
id,
name,
password,
nickname,
status,
create_time,
update_time
</sql> <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
<insert id="insert" parameterType="com.test.model.GodUser" >
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO god_user (
name,
password,
nickname,
status,
create_time,
update_time
) VALUES (
#{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{nickname,jdbcType=VARCHAR},
#{status,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP}
)
</insert> <insert id="insertSelective" parameterType="com.test.model.GodUser" >
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO god_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="password != null">
password,
</if>
<if test="nickname != null">
nickname,
</if>
<if test="status != null">
status,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="nickname != null">
#{nickname,jdbcType=VARCHAR},
</if>
<if test="status != null">
#{status,jdbcType=INTEGER},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert> <update id="updateByPrimaryKey" >
UPDATE god_user SET
name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
nickname = #{nickname,jdbcType=VARCHAR},
status = #{status,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
WHERE
id = #{id,jdbcType=INTEGER}
</update> <update id="updateByPrimaryKeySelective" >
UPDATE god_user SET
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="nickname != null">
nickname = #{nickname,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=INTEGER},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP}
</if>
WHERE
id = #{id,jdbcType=INTEGER}
</update> <delete id="deleteByPrimaryKey">
DELETE FROM god_user WHERE
id = #{id,jdbcType=INTEGER}
</delete> <select id="selectByPrimaryKey" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List" />
FROM god_user
WHERE
id = #{id,jdbcType=INTEGER}
</select> <sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql> <sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria"
separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql> <update id="updateByExample" parameterType="map">
UPDATE god_user SET
id = #{id,jdbcType=INTEGER},
name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
nickname = #{nickname,jdbcType=VARCHAR},
status = #{status,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update> <update id="updateByExampleSelective" parameterType="map">
UPDATE god_user SET
<if test="id != null">
id = #{id,jdbcType=INTEGER},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="nickname != null">
nickname = #{nickname,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=INTEGER},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP}
</if>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update> <delete id="deleteByExample" parameterType="com.test.model.GodUserExample">
delete from god_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete> <select id="countByExample" parameterType="com.test.model.GodUserExample" resultType="java.lang.Long">
select count(*) from god_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select> <select id="selectByExample" parameterType="com.test.model.GodUserExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from god_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by #{orderByClause}
</if>
</select> </mapper>
【Java】 rapid-generator 代码生成器的更多相关文章
- Java的generator工具类,数据库生成实体类和映射文件
首先需要几个jar包: freemarker-2.3.23.jar log4j-1.2.16.jar mybatis-3.2.3.jar mybatis-generator-core-1.3.2.ja ...
- java SSM 框架 代码生成器 websocket即时通讯 shiro redis
1. 权限管理:点开二级菜单进入三级菜单显示 角色(基础权限)和按钮权限 角色(基础权限): 分角色组和角色,独立分配菜单权限和增删改查权限. 按钮权限: 给角色分配按钮权限. ...
- mybatis generator代码生成器的使用
一.有关mybatis generator的使用可以查看如下网址:http://www.mybatis.org/generator/index.html 二.如下是我自己整理的学习步骤: <1& ...
- java SSM框架 代码生成器 快速开发平台 websocket即时通讯 shiro redis
A代码编辑器,在线模版编辑,仿开发工具编辑器,pdf在线预览,文件转换编码 B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,快速开发利器)+快速表单构建器 freemaker模版技术 , ...
- 【Java MyBatis Generator】使用generator自动生成Dao,Mapping和实体文件
具体请参照: http://blog.csdn.net/fengshizty/article/details/43086833 按照上面博客地址,下载Generator的依赖包: 如下是我的配置文件: ...
- Java UUID Generator(JUG)
UG 是一个纯 Java 的 UUID 生成器. UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的.通常平台会提供生成UUID的API.UUID按照开放软件基金 会 (OS ...
- Java之利用Freemarker模板引擎实现代码生成器,提高效率
https://blog.csdn.net/huangwenyi1010/article/details/71249258 java模板引擎freemarker代码生成器 更多 个人分类: 一步一步 ...
- Java语法笔记
目录 知识点 不支持 恶心事 与C#的区别 组件 学习资料 母版页 知识点 类 静态方法,即可以在类上被调用,也可以在实例对象上被调用. Java类 先执行静态构造函数,再执行静态方法或静态字段,所以 ...
- MyBatis Generator作为maven插件自动生成增删改查代码及配置文件例子
什么是MyBatis Generator MyBatis Generator (MBG) 是一个Mybatis的代码生成器,可以自动生成一些简单的CRUD(插入,查询,更新,删除)操作代码,model ...
随机推荐
- discuz论坛门户资讯入库接口【原创】
最近想打造一个社区门户站点,所以写了这个入库接口,可以对接数据入库. <?php /* * Discuz x3.2 门户免登陆发布接口 * 2018-08-10 * Copyright 68xi ...
- 在idea中调试spark程序-配置windows上的 spark local模式
spark程序大致有如下运行模式: standalone模式:spark自带的模式 spark on yarn:利用hadoop yarn来做集群的资源管理 local模式:主要在测试的时候使用, 这 ...
- (转载) 从0开始搭建SQL Server AlwaysOn 第一篇(配置域控)
安装完之后别忘了还需要安装SSMS,这是坑爹的地方之二,干嘛不集成到SQL Server安装包里还要用户自己单独下载 下载地址:https://msdn.microsoft.com/en-us/lib ...
- C# winform Panel 添加 滚动条
Detailed discussion here. Try this instead for 'only' scrolling vertical.(auto scroll needs to be fa ...
- 2-使用git管理一个单片机程序
https://www.cnblogs.com/yangfengwu/p/10842205.html 我用电脑压缩一个文件,然后通过git上传,然后在新买的linux系统通过wget 网络下载这个压缩 ...
- git 查看项目代码统计命令
git log --author="xxxxxxxx" --pretty=tformat: --numstat | gawk '{ add += $1 ; subs += $2 ; ...
- COGS 1583. [POJ3237]树的维护
二次联通门 : COGS 1583. [POJ3237]树的维护 /* COGS 1583. [POJ3237]树的维护 树链剖分 + 边权化点权 线段树 单点修改 + 区间取相反数 + 查询区间最大 ...
- 爬虫基础以及一个简单的实例(requests,re)
最近在看爬虫方面的知识,看到崔庆才所著的<Python3网络爬虫开发实战>一书讲的比较系统,果断入手学习.下面根据书中的内容,简单总结一下爬虫的基础知识,并且实际练习一下.详细内容请见:h ...
- 【概率论】5-7:Gama分布(The Gamma Distributions Part II)
title: [概率论]5-7:Gama分布(The Gamma Distributions Part II) categories: - Mathematic - Probability keywo ...
- Unity 绘制Mesh线条
using UnityEngine; using System.Collections; using System.Collections.Generic; public struct Segme ...