代码生成器

这个博客介绍了一种代码生成器的使用,它能够自动化创建包括领域模型(domain)、查询(query)、DAO、服务层接口和服务实现类以及Controller层的代码。通过宏定义和条件判断,该生成器可以智能地排除特定列并自动生成相应的get/set方法、类注释、包导入等。此外,还展示了如何生成JavaScript和JSP页面以支持前端展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.domain
##引入宏定义
$!define

##定义小写
#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##使用宏定义设置回调(保存位置与文件后缀)
#save("/main/java/cn/itsource/domain", “.java”)

##实现动态排除列
#set($temp = KaTeX parse error: Expected 'EOF', got '#' at position 24: …HashSet("id")) #̲foreach(item in KaTeX parse error: Expected 'EOF', got '#' at position 11: temp) #̲set(newList = KaTeX parse error: Expected 'EOF', got '#' at position 26: …rayList()) #̲foreach(column in KaTeX parse error: Expected 'EOF', got '#' at position 31: …olumn) #̲if(column.name!=KaTeX parse error: Expected 'EOF', got '#' at position 15: item) #̲#带有反回值的方法调用时使用tool.call来消除返回值
t o o l . c a l l ( tool.call( tool.call(newList.add($column))
#end
#end
##重新保存
t a b l e I n f o . s e t F u l l C o l u m n ( tableInfo.setFullColumn( tableInfo.setFullColumn(newList)
#end

##使用宏定义设置包后缀
#setPackageSuffix(“domain”)

##使用全局变量实现默认包导入
$!autoImport
import javax.persistence.*;

##使用宏定义实现类注释信息
#tableComment(“实体类”)
@Entity
@Table(name="$!{firstLowerName}")
public class KaTeX parse error: Expected '}', got '#' at position 40: …s BaseDomain { #̲foreach(column in KaTeX parse error: Expected 'EOF', got '#' at position 27: …ullColumn) #̲if({column.comment})//${column.comment}#end

private $!{tool.getClsNameByFullName($column.type)} $!{column.name};

#end

#foreach($column in KaTeX parse error: Expected 'EOF', got '#' at position 23: …fo.fullColumn) #̲#使用宏定义实现get,set…column)
#end

}
2.查询
##引入宏定义
$!define

#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##使用宏定义设置回调(保存位置与文件后缀)
#save("/main/java/cn/itsource/query", “query.java”)

##使用宏定义设置包后缀
#setPackageSuffix(“query”)

##使用全局变量实现默认包导入
! a u t o I m p o r t i m p o r t c n . i t s o u r c e . d o m a i n . !autoImport import cn.itsource.domain. !autoImportimportcn.itsource.domain.!{tableInfo.name};
import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
##使用宏定义实现类注释信息
#tableComment("$!{tableInfo.name}Query查询实体类")

public class ! t a b l e I n f o . n a m e Q u e r y e x t e n d s B a s e Q u e r y < !{tableInfo.name}Query extends BaseQuery< !tableInfo.nameQueryextendsBaseQuery<!{tableInfo.name}> {
private String name;
@Override
public Specification<KaTeX parse error: Expected '}', got 'EOF' at end of input: … Specification<!{tableInfo.name}> Specification= Specifications.<$!{tableInfo.name}>and()
.like(StringUtils.isNotBlank(name),“name”,"%+name+%")
.build();
return Specification;
}

public Sort getSort() {
    Sort sort = null;
    if(org.apache.commons.lang.StringUtils.isNotBlank(this.getOrderField())){
        Sort.Direction direction = Sort.Direction.DESC;
        if(org.apache.commons.lang.StringUtils.isNotBlank(this.getOrderType()) && "asc".equalsIgnoreCase(this.getOrderType())){
            direction = Sort.Direction.ASC;
        }
        Sort.Order order = new Sort.Order(direction, this.getOrderField());
        Sort.Order order01 = new Sort.Order(direction, "id");
        sort = new Sort(order,order01);
    }
    return sort;
}

@Override
public Pageable getPageable() {
    Pageable pageable = new PageRequest(this.getPageNo()-1, this.getPageSize(), this.getSort());
    return pageable;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}
3.dao
##引入宏定义
$!define

#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##使用宏定义设置回调(保存位置与文件后缀)
#save("/main/java/cn/itsource/query", “query.java”)

##使用宏定义设置包后缀
#setPackageSuffix(“query”)

##使用全局变量实现默认包导入
! a u t o I m p o r t i m p o r t c n . i t s o u r c e . d o m a i n . !autoImport import cn.itsource.domain. !autoImportimportcn.itsource.domain.!{tableInfo.name};
import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
##使用宏定义实现类注释信息
#tableComment("$!{tableInfo.name}Query查询实体类")

public class ! t a b l e I n f o . n a m e Q u e r y e x t e n d s B a s e Q u e r y < !{tableInfo.name}Query extends BaseQuery< !tableInfo.nameQueryextendsBaseQuery<!{tableInfo.name}> {
private String name;
@Override
public Specification<KaTeX parse error: Expected '}', got 'EOF' at end of input: … Specification<!{tableInfo.name}> Specification= Specifications.<$!{tableInfo.name}>and()
.like(StringUtils.isNotBlank(name),“name”,"%+name+%")
.build();
return Specification;
}

public Sort getSort() {
    Sort sort = null;
    if(org.apache.commons.lang.StringUtils.isNotBlank(this.getOrderField())){
        Sort.Direction direction = Sort.Direction.DESC;
        if(org.apache.commons.lang.StringUtils.isNotBlank(this.getOrderType()) && "asc".equalsIgnoreCase(this.getOrderType())){
            direction = Sort.Direction.ASC;
        }
        Sort.Order order = new Sort.Order(direction, this.getOrderField());
        Sort.Order order01 = new Sort.Order(direction, "id");
        sort = new Sort(order,order01);
    }
    return sort;
}

@Override
public Pageable getPageable() {
    Pageable pageable = new PageRequest(this.getPageNo()-1, this.getPageSize(), this.getSort());
    return pageable;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}
4.service层接口
##定义初始变量
#set($tableName = t o o l . a p p e n d ( " I " , tool.append("I", tool.append("I",tableInfo.name, “Service”))
##设置文件名称
! c a l l b a c k . s e t F i l e N a m e ( !callback.setFileName( !callback.setFileName(tool.append($tableName, “.java”))
##设置保存路劲
! c a l l b a c k . s e t S a v e P a t h ( !callback.setSavePath( !callback.setSavePath(tool.append($tableInfo.savePath, “/main/java/cn/itsource/Service”))

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}Service;

import ! t a b l e I n f o . s a v e P a c k a g e N a m e . d o m a i n . !{tableInfo.savePackageName}.domain. !tableInfo.savePackageName.domain.!{tableInfo.name};

/**

  • ! t a b l e I n f o . c o m m e n t ( !{tableInfo.comment}( !tableInfo.comment(!{tableInfo.name})Service层接口
  • @author $!author
  • @since $!time.currTime()
    */
    public interface ! t a b l e N a m e e x t e n d s I B a s e S e r v i c e < !{tableName} extends IBaseService< !tableNameextendsIBaseService<!{tableInfo.name}>{

}
5.service实现类
##定义小写
#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##定义初始变量
#set($tableName = t o o l . a p p e n d ( tool.append( tool.append(tableInfo.name, “ServiceImpl”))
##设置文件名称
! c a l l b a c k . s e t F i l e N a m e ( !callback.setFileName( !callback.setFileName(tool.append($tableName, “.java”))
##设置保存路劲
! c a l l b a c k . s e t S a v e P a t h ( !callback.setSavePath( !callback.setSavePath(tool.append($tableInfo.savePath, “/main/java/cn/itsource/Service/impl”))

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}Service.impl;

import ! t a b l e I n f o . s a v e P a c k a g e N a m e . d o m a i n . !{tableInfo.savePackageName}.domain. !tableInfo.savePackageName.domain.!{tableInfo.name};

import cn.itsource.repository.I ! t a b l e I n f o . n a m e R e p o s i t o r y ; i m p o r t c n . i t s o u r c e . s e r v i c e . I !{tableInfo.name}Repository; import cn.itsource.service.I !tableInfo.nameRepository;importcn.itsource.service.I!{tableInfo.name}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**

  • ! t a b l e I n f o . c o m m e n t ( !{tableInfo.comment}( !tableInfo.comment(!{tableInfo.name})Service层实现类
  • @author $!author
  • @since $!time.currTime()
    */

@Service
@Transactional(readOnly = true)
public class ! t a b l e N a m e e x t e n d s B a s e S e r v i c e I m p l < !{tableName} extends BaseServiceImpl< !tableNameextendsBaseServiceImpl<!{tableInfo.name}> implements I$!{tableInfo.name}Service{

@Autowired
private I$!{tableInfo.name}Repository $!{firstLowerName}Repository;

}
6.Controller层
##定义小写
#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##定义初始变量
#set($tableName = t o o l . a p p e n d ( tool.append( tool.append(tableInfo.name, “Controller”))
##设置文件名称
! c a l l b a c k . s e t F i l e N a m e ( !callback.setFileName( !callback.setFileName(tool.append($tableName, “.java”))
##设置保存路劲
! c a l l b a c k . s e t S a v e P a t h ( !callback.setSavePath( !callback.setSavePath(tool.append($tableInfo.savePath, “/main/java/cn/itsource/controller”))

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}controller;

import ! t a b l e I n f o . s a v e P a c k a g e N a m e . d o m a i n . !{tableInfo.savePackageName}.domain. !tableInfo.savePackageName.domain.!{tableInfo.name};
import cn.itsource.query. ! t a b l e I n f o . n a m e Q u e r y ; i m p o r t c n . i t s o u r c e . s e r v i c e . I !{tableInfo.name}Query; import cn.itsource.service.I !tableInfo.nameQuery;importcn.itsource.service.I!{tableInfo.name}Service;
import cn.itsource.utils.MyPage;
import cn.itsource.utils.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**

  • ! t a b l e I n f o . c o m m e n t ( !{tableInfo.comment}( !tableInfo.comment(!{tableInfo.name})Service层实现类
  • @author $!author
  • @since $!time.currTime()
    */

@Controller
@RequestMapping("/$!{firstLowerName}")
public class KaTeX parse error: Expected '}', got 'EOF' at end of input: …d private I!{tableInfo.name}Service $!{firstLowerName}Service;

@RequestMapping("/index")
public String index(){

    $!{tableInfo.name} $!{firstLowerName} = $!{firstLowerName}Service.findOne(1L);

    System.out.println($!{firstLowerName});

    Department department = employee.getDepartment();
    System.out.println(department);
    System.out.println(department.getClass());
    return "$!{firstLowerName}/$!{firstLowerName}";
}
/**
 * 分页查询数据
 * @ResponseBody注解表示[异步请求/不跳转页面]将当前方法的返回值(对象/List集合/Map集合/数组)使用第三方工具(jackson)自动转化为json格式的字符串
 * 放入响应的消息体中发送给浏览器
 * @param $!{firstLowerName}Query
 * @return
 */
@ResponseBody
@RequestMapping("/page")
public MyPage<$!{tableInfo.name}> page($!{tableInfo.name}Query $!{firstLowerName}Query){
    return $!{firstLowerName}Service.findByPage($!{firstLowerName}Query);
}

//新增
@ResponseBody
@RequestMapping("/save")
public ResultJson save($!{tableInfo.name} $!{firstLowerName}){
    try {
        $!{firstLowerName}Service.save($!{firstLowerName});
    } catch (Exception e) {
        e.printStackTrace();
        return new ResultJson(500,"操作失败:" + e.getMessage());
    }
    return new ResultJson(200,"ok");
}
//修改
@ModelAttribute("update")
public $!{tableInfo.name} findOneBeforeUpdate(Long id,String action){
    $!{tableInfo.name} one = null;
    if("update".equals(action) && id != null && id > 0){
        //查询出来的对象就一定是持久状态[一定与数据库中的数据完全一致]
        one = $!{firstLowerName}Service.findOne(id);
        //解决一下N to N错误
        one.setDepartment(null);
    }
    return one;
}



@ResponseBody
@RequestMapping("/findOne")
public $!{tableInfo.name} findOne(Long id){
    return $!{firstLowerName}Service.findOne(id);
}

//删除
@ResponseBody
@RequestMapping("/delete")
public ResultJson delete(String ids){
    try {
        $!{firstLowerName}Service.delete(ids);
    } catch (Exception e) {
        e.printStackTrace();
        return new ResultJson(500,"操作失败:" + e.getMessage());
    }
    return new ResultJson(200,"ok");
}

}
js
##定义小写
#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##定义初始变量
#set($tableName = t o o l . a p p e n d ( tool.append( tool.append(!{firstLowerName}, “$!{tableInfo.name}”))
##设置文件名称
! c a l l b a c k . s e t F i l e N a m e ( !callback.setFileName( !callback.setFileName(tool.append($tableName, “.js”))
##设置保存路劲
! c a l l b a c k . s e t S a v e P a t h ( !callback.setSavePath( !callback.setSavePath(tool.append( t a b l e I n f o . s a v e P a t h , " / m a i n / w e b a p p / j s / tableInfo.savePath, "/main/webapp/js/ tableInfo.savePath,"/main/webapp/js/!{firstLowerName}"))
$(function () {
/**
* easyui的datagrid要求后端返回的数据必须包含两个属性
* total 表示总行数
* rows 表示当前页要显示的数据集合
*/
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲dg').datagrid({…!{firstLowerName}/page’, //异步请求加载数据的地址
frozenColumns:[[{field:‘hhhh’,checkbox:true}]], //在表格左侧添加多选框
striped:true, //斑马线效果
method:“POST”, //请求方法 GET或者POST
pagination:true, //是否显示分页工具栏
rownumbers:true, //是否显示行号
toolbar:"#toolbar", //工具栏
columns:[[
#foreach($column in KaTeX parse error: Expected '}', got 'EOF' at end of input: … {field:'!{column.name}’,title:’$!{column.name}’,width:100},
#end
]]
});
//先通过表格获取到分页工具栏对象,然后再添加点击事件
$(’#dg’).datagrid(“getPager”).pagination({
onSelectPage:function(pageNumber, pageSize){
$(’#dg’).datagrid(‘loading’);
$("#pageNo").val(pageNumber);
$("#pageSize").val(pageSize);
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲dg').datagrid('…("#searchForm").toJSON());
$(this).pagination({//给分页工具栏设置一下底部的当前页码以及每页显示的行数
pageNumber:pageNumber,
pageSize:pageSize
});
$(’#dg’).datagrid(‘loaded’);
}
});
//给所有按钮绑定点击
KaTeX parse error: Expected '}', got 'EOF' at end of input: …var methodName=(this).attr(“data-method”);
window.methodsmethodName;
})
});
window.methods={
search:function () {
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲dg').datagrid('…("#searchForm").toJSON())
//要实现翻页只需要传递两个请求参数pageNo和pageSize给后端即可
$(’#dg’).datagrid(‘load’, $("#searchForm").toJSON());
$(’#dg’).datagrid(“getPager”).pagination({//给分页工具栏设置一下底部的当前页码以及每页显示的行数
pageNumber:1,
pageSize:10
});
$(’#dg’).datagrid(‘loaded’);
},
add:function () {
$("#dialog").dialog(“open”); //打开一个模态框
//重置表单
$("#aaa").form(“reset”);

},
save:function () {
    var param = $("#aaa").toJSON();
    var url="$!{firstLowerName}/save";
    if (param.id){
        //id没有值就修改
        url="$!{firstLowerName}/update";
    }
    $.post("/$!{firstLowerName}/save",param,function (data) {
        if(data.status == 200){
            $.messager.alert("消息", data.msg, "info");
            //新增成功要刷新表格数据
            $('#dg').datagrid('loading');
            $("#pageNo").val(1);
            $("#pageSize").val(10);
            //要实现翻页只需要传递两个请求参数pageNo和pageSize给后端即可
            $('#dg').datagrid('load', $("#searchForm").toJSON());
            $('#dg').datagrid("getPager").pagination({//给分页工具栏设置一下底部的当前页码以及每页显示的行数
                pageNumber:1,
                pageSize:10
            });
            $('#dg').datagrid('loaded');
            //关闭模态框
            $("#dialog").dialog("close");
        }else{
            $.messager.alert("错误", data.msg, "error");
        }
    },"json");
},
edit:function () {
    var selectedRows=$("#dg").datagrid("getSelections");
    if (selectedRows.length==0) {
        $.messager.alert("错误","请选择要编辑的数据","error");
        return;
    }
    if (selectedRows.length>1){
        $.messager.alert("错误","只能选择一条数据","error");
        return;
    }
    //通过当前id去查询 ··
    $.getJSON("/$!{firstLowerName}/findOne",{id:selectedRows[0].id},function ($!{firstLowerName}) {
        //回填表单
        $("#aaa").form("load",$!{firstLowerName});
        //关联对象要手动回填
        //$("#departmentId2").combobox("setValue",$!{firstLowerName}.department.id);
        //隐藏密码框设置为禁用
        $("#passwordBox").hide();
        $("#passwordBox>input[name=password]").prop("disabled",true);
    })
    //打开模态框
    $("#dialog").dialog("open");
},
remove:function () {
    var selectedRows=$("#dg").datagrid("getSelections");
    if (selectedRows.length==0) {
        $.messager.alert("错误","请选择要删除的数据","error");
        return;
    }
    $.messager.confirm('确认','您确认想要删除数据吗?',function(r){
        if (r){
            var ids=[];
            for (var i=0;i<selectedRows.length;i++) {
                ids.push(selectedRows[i].id);
            }
            $.getJSON("/$!{firstLowerName}/delete",{ids:ids.join(",")},function (data) {
                if(data.status == 200){
                    $.messager.alert("消息", data.msg, "info");
                    //新增成功要刷新表格数据
                    $('#dg').datagrid('loading');
                    $("#pageNo").val(1);
                    $("#pageSize").val(10);
                    //要实现翻页只需要传递两个请求参数pageNo和pageSize给后端即可
                    $('#dg').datagrid('load', $("#searchForm").toJSON());
                    $('#dg').datagrid("getPager").pagination({//给分页工具栏设置一下底部的当前页码以及每页显示的行数
                        pageNumber:1,
                        pageSize:10
                    });
                    $('#dg').datagrid('loaded');
                    //关闭模态框
                    $("#dialog").dialog("close");
                }else{
                    $.messager.alert("错误", data.msg, "error");
                }
            })
        }
    });

},
cancel:function () {
    $("#dialog").dialog("close");
}

}
jsp
##定义小写
#set( f i r s t L o w e r N a m e = firstLowerName= firstLowerName=tool.firstLowerCase($!{tableInfo.name}))

##实现动态排除列
#set($temp = KaTeX parse error: Expected 'EOF', got '#' at position 24: …HashSet("id")) #̲foreach(item in KaTeX parse error: Expected 'EOF', got '#' at position 11: temp) #̲set(newList = KaTeX parse error: Expected 'EOF', got '#' at position 26: …rayList()) #̲foreach(column in KaTeX parse error: Expected 'EOF', got '#' at position 31: …olumn) #̲if(column.name!=KaTeX parse error: Expected 'EOF', got '#' at position 15: item) #̲#带有反回值的方法调用时使用tool.call来消除返回值
t o o l . c a l l ( tool.call( tool.call(newList.add($column))
#end
#end
##重新保存
t a b l e I n f o . s e t F u l l C o l u m n ( tableInfo.setFullColumn( tableInfo.setFullColumn(newList)
#end

##定义初始变量
#set($tableName = t o o l . a p p e n d ( tool.append( tool.append(!{firstLowerName}, “$!{tableInfo.name}”))
##设置文件名称
! c a l l b a c k . s e t F i l e N a m e ( !callback.setFileName( !callback.setFileName(tool.append($tableName, “.jsp”))
##设置保存路劲
! c a l l b a c k . s e t S a v e P a t h ( !callback.setSavePath( !callback.setSavePath(tool.append( t a b l e I n f o . s a v e P a t h , " / m a i n / w e b a p p / W E B − I N F / v i e w s / tableInfo.savePath, "/main/webapp/WEB-INF/views/ tableInfo.savePath,"/main/webapp/WEBINF/views/!{firstLowerName}"))

<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

$!{tableInfo.name}管理页面 <%@include file="/WEB-INF/views/common.jsp"%>

#foreach($column in t a b l e I n f o . f u l l C o l u m n ) < d i v c l a s s = " f o r m − g r o u p " > 用 户 : < i n p u t t y p e = " t e x t " n a m e = " tableInfo.fullColumn) <div class="form-group"> 用户:<input type="text" name=" tableInfo.fullColumn)<divclass="formgroup"><inputtype="text"name="!{column.name}" placeholder="$!{column.name}" class=“easyui-validatebox in”>

#end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值