前言
首先介绍一下 我是一个写过很多年.net 代码的程序员
2010年才转的JAVA开发
所以一直对@李天平 .net大神级人物 心生崇拜
此人博客地址为 https://blog.csdn.net/litp/
提到这个人 就不得不提起 动软代码生成器 真乃神器也
但是JAVA web开发中 一直没有一款顺手的 代码生成器
后来公司胡总写了一个 但是修改起来 非得有很强的技术实力不可
于是想到用这个动软代码生成器来逆向生成SpringBoot 代码
具体模板使用方法请参考官方解释
https://blog.csdn.net/litp/article/details/6445672
Entity模板
所有表名为 t_ 开头 用户表就是 t_user
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
host.Fieldlist.Sort(CodeCommon.CompareByintOrder);
boolean hasDefaultValue = true;
#>
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;
import org.springframework.data.rest.core.annotation.RestResource;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="<#= host.GetModelClass(host.TableName) #>")
public class <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>{
<# foreach (ColumnInfo c in host.Fieldlist)
{ #>
<# if(c.IsPrimaryKey ){#>@Id
@GeneratedValue(strategy = GenerationType.AUTO)<#}#><#= c.TypeName=="longtext" ? @"@Lob //不建议在主表放置大型文本字段 如果有 推荐使用 一对一关联表存放" : "" #>
private <#= typeConvert(c.TypeName)#> <#= c.ColumnName.ToString()#><#=hasDefaultValue?getDefaultValueByType(c.TypeName):""#>;
<#}#>
<# foreach (ColumnInfo c in host.Fieldlist)
{ #>
public <#= typeConvert(c.TypeName)#> get<#= c.ColumnName.ToString().Substring(0,1).ToUpper()#><#= c.ColumnName.ToString().Substring(1)#>() {
return <#= c.ColumnName.ToString()#>;
}
public void set<#= c.ColumnName.ToString().Substring(0,1).ToUpper()#><#= c.ColumnName.ToString().Substring(1)#>(<#= typeConvert(c.TypeName)#> <#= c.ColumnName.ToString()#>) {
this.<#= c.ColumnName.ToString()#> = <#= c.ColumnName.ToString()#>;
}
<#}#>
}
<#+
//
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
//mysql to java
//include varchar char longtext int bigint float double bit date real
//default type String
private string typeConvert(string type){
string str2 = "String";
if(type=="int"||type=="mediumint"||type=="integer"||type=="smallint"||type=="tinyint"){
str2 = "Integer";
}else if(type=="float"){
str2 = "Float";
}else if(type=="double"||type=="real"){
str2 = "Double";
}else if(type=="bigint"){
str2 = "Long";
}else if(type=="bit"){
str2 = "Boolean";
}else if(type=="date"||type=="datetime"||type=="timestamp"){
str2 = "Date";
}
return str2;
}
private string getDefaultValueByType(string type){
string str2 = " = \"\"";
if(type=="int"||type=="mediumint"||type=="integer"||type=="smallint"||type=="tinyint"){
str2 = " = 0";
}else if(type=="float"){
str2 = " = 0f";
}else if(type=="double"||type=="real"){
str2 = " = 0d";
}else if(type=="bigint"){
str2 = " = 0l";
}else if(type=="bit"){
str2 = " = false";
}else if(type=="date"||type=="datetime"||type=="timestamp"){
str2 = " = new Date()";
}
return str2;
}
#>
Repository
生成 几行代码而已啦 包含的Entity包名需要更改
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
#>
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avicsafety.webapp.entity.<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>; //请自行修改
@Repository
public interface <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>Repository extends JpaRepository<<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>, Long> {
}
<#+
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
#>
Service 层代码
我写了个接口和类 来对应JPA常用方法
import java.io.Serializable;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* 基础的Service 接口 继承次接口 就有了 JPA了大部分方法
* @author shili
*
*/
public interface IService<T,ID extends Serializable> {
/**
* <p>
* 插入一条记录 返回这个对象的实体
* </p>
*
* @param entity 实体对象
* @return T
*/
T insert(T entity);
/**
* <p>
* 插入多个实体
* </p>
*
* @param entityList 实体对象列表
* @return List
*/
List<T> insert(List<T> entityList);
/**
* <p>
* 更新操作 通过id
* </p>
* @param entity 实体对象列表
* @param id
* @return 这个对象
*/
T update(T entity, ID id);
/**
* <p>
* 更新操作 通过条件批量更新
* </p>
* @param 需要更新成啥样 这个里面是update 语句中 set部分
* @param 给定的条件是一个实体 实体中的字段就是条件 这个是条件 不要弄反了 这个就是update 语句中 where部分
* @return 影响的条目数
*/
Integer update(T entity,T where);
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
* @return boolean
*/
void delete(ID id);
/**
* <p>
* 根据 实体 删除 符合这个实体中字段条件的 都删除
* </p>
*
* @param 给定的条件是一个实体 实体中的字段就是条件
* @return 删除的条目数
*/
Integer deleteByBody(T where);
/**
* <p>
* 通过条件批量删除
* </p>
*
* @param id 主键ID
* @return T
*/
T findOne(ID id);
/**
* <p>
* 查询(根据ID 批量查询)
* </p>
*
* @param idList 主键ID列表
* @return List<T>
*/
List<T> findByIds(Iterable<ID> ids);
/**
* <p>
* 列出所有
* </p>
*
* @return List<T>
*/
List<T> findAll();
/**
* <p>
* 列出所有
* </p>
*
* @return Page<T>
*/
Page<T> findAll(Pageable pageable);
/**
* <p>
* 查询(根据 Body 条件)
* </p>
*
* @param Body 对象实体
* @return List<T>
*/
List<T> findByBody(T t);
/**
* <p>
* 查询(根据 Body)
* </p>
*
* @param Body 对象实体
* @return Page<T>
*/
Page<T> findByBody(T t,Pageable pageable);
/**
* <p>
* 查询总记录数
* </p>
*
* @param wrapper 实体对象
* @return Long
*/
Long count();
/**
* <p>
* 根据 Body 条件,查询总记录数
* </p>
*
* @param wrapper 实体对象
* @return Long
*/
Long count(T t);
}
实现
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.avicsafety.webapp.base.service.IService;
/**
* 其实Service 继承他就很好了
* @author shili
*
* @param Repository
* @param entity
* @param 主键类型
*/
public class ServiceImpl<M extends JpaRepository<T,ID>,T,ID extends Serializable> implements IService<T,ID> {
@Autowired
protected M dao;
@Override
public T insert(T entity) {
return dao.save(entity);
}
@Override
public List<T> insert(List<T> entities) {
return dao.save(entities);
}
@Override
public T update(T entity, ID id) {
T t= dao.findOne(id);
BeanUtils.copyProperties(entity, t);
return dao.save(t);
}
@Override
public void delete(ID id) {
dao.delete(id);;
}
@Override
public T findOne(ID id) {
return dao.findOne(id);
}
@Override
public List<T> findByIds(Iterable<ID> ids) {
return dao.findAll(ids);
}
@Override
public List<T> findAll() {
return dao.findAll();
}
@Override
public Page<T> findAll(Pageable pageable) {
return dao.findAll(pageable);
}
@Override
public Long count() {
return dao.count();
}
@Override
public Long count(T t) {
return dao.count(Example.of(t));
}
@Override
public List<T> findByBody(T t) {
return dao.findAll(Example.of(t));
}
@Override
public Page<T> findByBody(T t,Pageable pageable) {
return dao.findAll(Example.of(t), pageable);
}
@Override
public Integer update(T entity, T where) {
List<T> _list = findByBody(where);
for(T t:_list) {
BeanUtils.copyProperties(entity, t);
}
dao.save(_list);
return _list.size();
}
@Override
public Integer deleteByBody(T where) {
List<T> _list = findByBody(where);
dao.delete(_list);
return _list.size();
}
}
生成代码模板 就超级简单了 首先是接口
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
#>
public interface <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>Service extends IService<<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>,Long> {
}
<#+
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
#>
然后是实现
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
#>
import org.springframework.stereotype.Service;
public class <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>ServiceImpl extends ServiceImpl<<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>Repository,<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>,Long> implements IStockService{
}
<#+
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
#>
Controller 层
这里是 resful 风格 好吧 对付着用吧
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
#>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>Controller {
@Autowired
<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>Service <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service;
@RequestMapping(value = "/public/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>/{id}",method = RequestMethod.GET)
public <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> findOne(@PathVariable("id") Long id) {
return <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.findOne(id);
}
@RequestMapping(value = "/public/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>",method = RequestMethod.GET)
public Page<<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>> findAll(Pageable pageable) {
return <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.findAll(pageable);
}
//按照规范 应该使用GET方式 但是POSTMAN不方便测试
@RequestMapping(value = "/public/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>/search/findByBody",method = RequestMethod.POST)
public Page<<#= getClassNameByTableName(host.GetModelClass(host.TableName)) #>> findByBody(@RequestBody <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> entity,Pageable pageable) {
return <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.findByBody(entity, pageable);
}
@RequestMapping(value = "/public/goods",method = RequestMethod.POST)
public <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> insert(@RequestBody <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> entity) {
return <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.insert(entity);
}
@RequestMapping(value = "/public/goods",method = RequestMethod.PUT)
public <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> update(@RequestBody <#= getClassNameByTableName(host.GetModelClass(host.TableName)) #> entity) {
return <#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.update(entity,entity.getId()); //获取主键值的方法 请自行修改
}
@RequestMapping(value = "/public/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>/{id}",method = RequestMethod.DELETE)
public void delete(@PathVariable("id") Long id) {
<#= getNameByTableName(host.GetModelClass(host.TableName)) #>Service.delete(id);
}
}
<#+
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
private string getNameByTableName(string tname){
return tname.Replace("t_","");
}
#>
页面
前台使用Bootstrap + Vue 具体点应该说是AdminLET
html部分
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
host.Fieldlist.Sort(CodeCommon.CompareByintOrder);
#>
<<#= getChar() #>include "../../template/layout.html"/>
<@title>
列表
</@title>
<@html>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
列表
</h1>
<ol class="breadcrumb">
<li><a href="../index/home.html"><i class="fa fa-dashboard"></i> 首页</a></li>
<li class="active">列表</li>
</ol>
</section>
<!-- Main content -->
<section class="content" v-cloak>
<div class="row">
<div class="col-md-12">
<div class="pull-left">
<button type="button" class="btn btn-primary" @click="openPanle(0)">新建</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="box box-primary">
<div class="box-body no-padding">
<v-table
is-horizontal-resize
style="width:100%"
:columns="columns"
:table-data="list"
@on-custom-comp="table_opera"
:paging-index="(pageIndex)*pageSize"
row-hover-color="#eee"
even-bg-color="#f2f2f2"
:show-vertical-border="false"></v-table>
</div>
<div class="box-footer">
<v-pagination @page-change="pageChange" :total="totalElements" :page-size="pageSize" :layout="['total', 'prev', 'pager', 'next', 'jumper']"></v-pagination>
</div>
<!-- /.box body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-12">
<div class="pull-left">
<button type="button" class="btn btn-primary bottom10px" @click="openPanle(0)">新建</button>
</div>
</div>
</div>
</section>
<!-- /.content -->
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="myform">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
</div>
<!-- /.modal-header -->
<div class="modal-body">
<# foreach (ColumnInfo c in host.Fieldlist){ #>
<div class="form-group">
<label ><#= c.ColumnName.ToString()#></label>
<input type="text" class="form-control" id="<#= c.ColumnName.ToString()#>" name="<#= c.ColumnName.ToString()#>" placeholder="<#= c.ColumnName.ToString()#>" v-model='info.<#= c.ColumnName.ToString()#>'>
</div>
<#}#>
</div>
<!-- /.modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" @click="save">保存</button>
</div>
<!-- /.modal-footer -->
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</@html>
<@myscript>
<script src="../../js/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>.js"></script>
</@myscript>
<#+
private string getClassNameByTableName(string tname){
string str2 = "";
tname = tname.Replace("t_","");
for (int i = 0; i < tname.Length; i++) {
string temp = tname.Substring(i, 1);
if (temp == "_") {
temp = tname.Substring(i+1, 1).ToUpper();
i++;
}
if(i==0){
temp = temp.ToUpper();
}
str2 += temp;
}
return str2;
}
private string getNameByTableName(string tname){
return tname.Replace("t_","");
}
private string getChar(){
return "#";
}
#>
js部分
<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".java" #>
<#
TableHost host = (TableHost)(Host);
host.Fieldlist.Sort(CodeCommon.CompareByintOrder);
#>
var vm = new Vue({
el: '#content',
data: {
index:0,
info:{},
list:[],
page:0,
columns: [
<# foreach (ColumnInfo c in host.Fieldlist){ #>
{field: '<#= c.ColumnName.ToString()#>', title:'<#= c.ColumnName.ToString()#>', width: 100, titleAlign: 'center',columnAlign:'center', isResize:true},
<#}#>
{field: 'custome-adv', title: '操作', width: 100, titleAlign: 'center',columnAlign:'center',componentName:'table-operation'}
],
pageIndex: 0,
pageSize:14,
totalElements:0,
totalPages:0
},
methods: {
init: function () {
this.load();
},
load:function(){
this.$http.get(HOST_NAME+'/api/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>',
{params:{page:this.pageIndex,size:this.pageSize,sort:"id,desc"}}).then(function (response) {
vm.list = response.data.content;
vm.totalPages = response.data.totalPages;
vm.totalElements = response.data.totalElements;
},function (error) {
layer.open({ontent: '与服务器通信出错',btn: '确定'});
});
},
openPanle:function(type){
if(type==0){
this.info={};
}else{
this.info=this.list[this.index];
}
$('#myModal').modal('show');
},
save:function(){
if(!this.info.id){
this.$http.post(HOST_NAME+'/api/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>',this.info)
.then(function(response){
this.list[this.index].push(response.data);
$('#myModal').modal('hide');
layer.open({content:"操作成功!",btn:"确认"});
},function(response){
layer.open({content:"访问服务器出错,请稍后再试!",btn:"确定"});
});
}else{
this.$http.put(HOST_NAME+'/api/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>',this.info)
.then(function(response){
this.list[this.index] = response.data;
$('#myModal').modal('hide');
layer.open({content:"操作成功!",btn:"确认"});
},function(response){
layer.open({content:"访问服务器出错,请稍后再试!",btn:"确定"});
});
}
},
del:function(index,id){
layer.open({
content: '真的要删除吗?'
,btn: ['确定', '取消']
,yes: function(e){
layer.close(e);
var url = HOST_NAME + '/api/<#= getNameByTableName(host.GetModelClass(host.TableName)) #>/'+id;
Vue.http.delete(url).then(function (response) {
vm.list.splice(index, 1);
layer.open({content: '成功',btn:"确认"});
}, function (response) {
layer.open({content:"访问服务器出错,请稍后再试!",btn:"确认"});
});
}
});
},
table_opera(params){
console.log(params);
if (params.type === 'delete'){ // do delete operation
this.del(params.index,params.rowData["id"]);
}else if (params.type === 'edit'){ // do edit operation
this.index = params.index;
this.openPanle(1);
}
},
pageChange:function(pageIndex){
this.pageIndex = pageIndex-1;
this.load();
},
pageSizeChange:function(pageSize){
this.pageIndex = 0;
this.pageSize = pageSize;
this.load();
}
}
});
vm.init();
// 自定义列组件
Vue.component('table-operation',{
template:`<span>
<a href="" @click.stop.prevent="edit(rowData,index)">修改</a>
<a href="" @click.stop.prevent="deleteRow(rowData,index)">删除</a>
</span>`,
props:{
rowData:{
type:Object
},
field:{
type:String
},
index:{
type:Number
}
},
methods:{
edit(){
let params = {type:'edit',index:this.index,rowData:this.rowData};
this.$emit('on-custom-comp',params);
},
deleteRow(){
let params = {type:'delete',index:this.index,rowData:this.rowData};
this.$emit('on-custom-comp',params);
}
}
})
<#+
private string getNameByTableName(string tname){
return tname.Replace("t_","");
}
#>
如果本文对您有帮助 请留言