自建生成代码工具(暂支持Spring boot +JPA)(更新中)

Posted markdev

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自建生成代码工具(暂支持Spring boot +JPA)(更新中)相关的知识,希望对你有一定的参考价值。

我们努力的方向就是用更少的时间写出更高质量的代码,因此我们都需要借助一些工具来提高自己的开发效率。写代码有些年头了,慢慢的可以写一些东西来提高工作效率。主要会从Java后台和android开始,暂时叫“Auto coding”,大家如果有更好的想法麻烦告诉我,谢谢。

1. 生成后台和管理端代码 

  往往我们做项目会先把表建好再进行编码,管理端有多相似的地方,所以通过表SQL利用AutoCoding所以大部分代码,再对部分部分地方手动调整就能先快速完成一个功能模块。

  Spring boot JPA + layui 结构为例,暂时可以生成Entity、EntityModel、Repository、Service、ServiceImpl、Controller、list.jsp(数据列表功能)、add.jsp(新建数据功能)、update.jsp(更新数据功能)、detail.jsp(详情功能)。

  

示例:

用户表

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ID,
  `account` varchar(50) NOT NULL COMMENT 账号,
  `password` varchar(50) NOT NULL COMMENT 密码,
  `nickname` varchar(20) NOT NULL COMMENT 昵称,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

下面是生成的相关代码

 

技术分享图片
import javax.persistence.*;

/**
 *
 * Created by Harlan on 2018-05-03 16:44:14.
 */

@Entity
@Table(name = "user")
public class User extends BaseEntity{

    // 账号
    @Column(name = "account")
    private String account;
 
    // 密码
    @Column(name = "password")
    private String password;
 
    // 昵称
    @Column(name = "nickname")
    private String nickname;
 
    public String getAccount() {
        return account;
    }
 
    public void setAccount(String account) {
        this.account = account;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getNickname() {
        return nickname;
    }
 
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}
Entity
技术分享图片
/**
 *
 * Created by Harlan on 2018-05-03 16:44:14.
 */
public class UserViewModel {
    // ID
    private Integer id;

    // 账号
    private String account;

    // 密码
    private String password;

    // 昵称
    private String nickname;
 
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }
 
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}
Model
技术分享图片
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

/**
 * Created by Harlan on 2018-05-03 16:44:14.
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long>,JpaSpecificationExecutor<User> {
}
Repository
技术分享图片
import org.springframework.stereotype.Service;

/**
 * Created by Harlan on 2018-05-03 16:44:14.
 */
@Service
public interface UserService {

    void addUser(UserViewModel model);

    void updateUser(UserViewModel model);

    UserViewModel getUserDetail(long id);

    BaseResponseList<UserViewModel> getUserPage(BaseQuery query);

    void deleteUser(Long[] ids);
}
Service
技术分享图片
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Harlan on 2018-05-03 16:44:14.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void addUser(UserViewModel model) {
        User user = new User();
        user.setId(model.getId());
        user.setAccount(model.getAccount());
        user.setPassword(model.getPassword());
        user.setNickname(model.getNickname());
        userRepository.save(user);
    }

    @Override
    public void updateUser(UserViewModel model){
        User user = userRepository.findOne(model.getId());
        user.setId(model.getId());
        user.setAccount(model.getAccount());
        user.setPassword(model.getPassword());
        user.setNickname(model.getNickname());
        userRepository.save(user);
    }

    @Override
    public UserViewModel getUserDetail(long id){
        User user = userRepository.findOne(id);
        UserViewModel model = new UserViewModel();
        if(user == null) {
            return model;
        }
        model.setId(user.getId());
        model.setAccount(user.getAccount());
        model.setPassword(user.getPassword());
        model.setNickname(user.getNickname());
        return model;
    }

    @Override
    public BaseResponseList<UserViewModel> getUserPage(BaseQuery query){
        List<Sort.Order> orders = new ArrayList<>();
        Sort sort = null;
        if (!StringUtils.isEmpty(query.getField())) {
            orders.add(new Sort.Order("asc".equalsIgnoreCase(query.getOrder()) ? Sort.Direction.ASC : Sort.Direction.DESC, query.getField()));
            sort = new Sort(orders);
        }
        Page<User> page = userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                // TODO 加过滤条件
                Predicate[] pre = new Predicate[predicate.size()];
                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        }, new PageRequest(query.getPage() - 1, query.getLimit(),sort));
        BaseResponseList<UserViewModel> result = new BaseResponseList<>();
        result.setCount(page.getTotalElements());
        List<UserViewModel> models = new ArrayList<>();
        List<User> users = page.getContent();
        for (User user : users) {
            UserViewModel model = new UserViewModel();
            model.setId(user.getId());
            model.setAccount(user.getAccount());
            model.setPassword(user.getPassword());
            model.setNickname(user.getNickname());
            models.add(model);
        }
        result.setData(models);
        return result;
    }

    @Override
    public void deleteUser(Long[] ids) {
        for (Long id : ids) {
            User user = userRepository.findOne(id);
            // TODO 根据实际情况修改
            user.setDeleted(true);
            userRepository.save(user);
        }
    }
}
ServiceImpl
技术分享图片
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Harlan on 2018-05-03 16:44:14.
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/userView")
    public ModelAndView userView() {
        ModelAndView modelAndView = new ModelAndView("/user");
        return modelAndView;
    }

    @RequestMapping(value = "/addUserView")
    public ModelAndView addUserView() {
        ModelAndView modelAndView = new ModelAndView("/userAdd");
        return modelAndView;
    }

    @RequestMapping(value = "/updateUserView")
    public ModelAndView editUserView(@RequestParam Long id) {
        ModelAndView model = new ModelAndView("/userUpdate");
        UserViewModel userModel = userService.getUserDetail(id);
        model.addObject("user", userModel);
        return model;
    }

    @RequestMapping(value = "/addUser")
    public BaseResponse addUser(UserViewModel model){
        userService.addUser(model);
        return success();
    }

    @RequestMapping(value = "/updateUser")
    public BaseResponse updateUser(UserViewModel model){
        userService.updateUser(model);
        return success();
    }

    @RequestMapping(value = "/getUserPage")
    public BaseResponseList getUserPage(BaseQuery query){
        return userService.getUserPage(query);
    }

    @RequestMapping(value = "/getUserDetail")
    public BaseResponse getUserDetail( @RequestParam Long id){
        return success(userService.getUserDetail(id));
    }

    @RequestMapping(value = "/deleteUser")
    public BaseResponse deleteUser( @RequestParam Long[] ids){
        userService.deleteUser(ids);
        return success();
    }
}
Controller
技术分享图片
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>User</title>
</head>
<body>
<jsp:include page="../nav.jsp"></jsp:include>
<div class="content-body">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>User</legend>
    </fieldset>

    <form id="user-form">
        <div class="layui-row layui-col-space10 ">
            <div class="layui-col-md2">
                <div class="layui-btn-group">
                    <a class="layui-btn layui-btn-sm btn-add">
                        <i class="layui-icon">&#xe654;</i>
                    </a>
                    <a class="layui-btn layui-btn-sm btn-update">
                        <i class="layui-icon">&#xe642;</i>
                    </a>
                    <a class="layui-btn layui-btn-sm btn-delete">
                        <i class="layui-icon">&#xe640;</i>
                    </a>
                </div>
            </div>
            <div class="layui-col-md2 ">
                <input type="text" name="name" placeholder="名称" autocomplete="off"class="layui-input">
            </div>

            <div class="layui-col-md1">
                <a class="layui-btn" id="search">搜索</a>
            </div>
        </div>
    </form>

    <table id="table" lay-filter="user">
    </table>
</div>

<script>
    layui.use([element, table, jquery], function () {
        var element = layui.element;
        var table = layui.table;
        var $ = layui.jquery;

        table.render({
            elem: #table,
            id: "user-table",
            url: /user/getUserPage,
            page: true,
            height: full-200,
            limit:20,
            initSort: {
                field: id
                ,type: desc
            },
            where:{
                field: id
                ,order: desc
            },
            cols: [[
                {checkbox: true},
             {field: id, title: ID, width: 100},
             {field: account, title: 账号, width: 100},
             {field: password, title: 密码, width: 100},
             {field: nickname, title: 昵称, width: 100},

            ]]
        });

        $(".btn-add").on("click", function () {
            layer.open({
                formType: 2,
                type: 2,
                content: /user/addUserView,
                title: 添加User,
                area: [700px, 500px],
                end: function () {
                    table.reload("user-table");
                }
            });
        });

        $(".btn-update").on("click", function () {
            var checkData = table.checkStatus(user-table).data;
            if (checkData.length != 1) {
                layer.msg("请选中一条记录编辑!");
                return;
            }
            var id = checkData[0].id;
            layer.open({
                formType: 2,
                type: 2,
                content: /user/updateUserView?id= + id,
                title: 编辑User,
                area: [700px, 500px],
                end: function () {
                    table.reload("user-table");
                }
            });
        });

        $(".btn-delete").on("click", function () {
            var checkData = table.checkStatus(user-table).data;
            if (checkData.length < 1) {
                layer.msg("请选中要删除的数据!");
                return;
            }
            layer.confirm(您确定要删除这 + checkData.length + 条数据吗?, {
                btn: [确认, 取消]
            }, function (index) {
                layer.close(index);
                var ids = new Array();
                $.each(checkData, function (index, val) {
                    ids.push(val.id);
                });

                $.post("/user/deleteUser", {ids: ids.join(",")}, function (data) {
                    if (data.code === 0) {
                        layer.msg(删除成功, {icon: 1});
                        location.reload();
                        table.reload("user-table");
                    } else {
                        layer.alert(data.msg, {icon: 5});
                    }
                }, "json");
            });
        });

        $("#search").on("click", function () {
            var data = serializeArrayToSerializeObject($, $("#user-form").serializeArray());
            table.reload("user-table", {
                page: {
                    curr: 1
                }
                , where: data
            });
        });

        table.on(sort(user), function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
            table.reload(user-table, {
                initSort: obj
                ,where: {
                    field: obj.field
                    ,order: obj.type
                }
            });
        });
    });
</script>
</body>
</html>
list.jsp
技术分享图片
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User</title>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/css/base.css">
</head>
<body>
<div class="content-body">
    <form class="layui-form" action="">

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>ID</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘id‘> 
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>账号</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘account‘> 
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>密码</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘password‘> 
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>昵称</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘nickname‘> 
          </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="{htmlName}">立即提交</button>
            </div>
        </div>

    </form>
</div>

<script src="<%=request.getContextPath()%>/layui/layui.js"></script>
<script>
    layui.use([form, jquery, element], function () {
        var form = layui.form;
        var $ = layui.jquery;
        var element = layui.element;
        form.on(submit({htmlName}), function (data) {
            var params = data.field;
            $.post("<%=request.getContextPath()%>/user/addUser", params, function (data) {
                if (data.code === 0) {
                    parent.layer.closeAll();
                } else {
                    layer.alert(data.msg, {icon: 5});
                }
            }, "json");
            return false;
        });
    });
</script>
</body>
</html>
add.jsp
技术分享图片
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User</title>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/css/base.css">
</head>
<body>
<div class="content-body">
    <form class="layui-form" action="">
        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>ID</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘id‘ value=‘${user.id}‘>
          </div>
        </div>
        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>账号</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘account‘ value=‘${user.account}‘>
          </div>
        </div>
        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>密码</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘password‘ value=‘${user.password}‘>
          </div>
        </div>
        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>昵称</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ lay-verify=‘required‘ name=‘nickname‘ value=‘${user.nickname}‘>
          </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="{htmlName}">立即提交</button>
            </div>
        </div>

    </form>
</div>

<script src="<%=request.getContextPath()%>/layui/layui.js"></script>
<script>
    layui.use([form, jquery, element], function () {
        var form = layui.form;
        var $ = layui.jquery;
        var element = layui.element;
        form.on(submit({htmlName}), function (data) {
            var params = data.field;
            $.post("<%=request.getContextPath()%>/user/updateUser", params, function (data) {
                if (data.code === 0) {
                    parent.layer.closeAll();
                } else {
                    layer.alert(data.msg, {icon: 5});
                }
            }, "json");
            return false;
        });
    });
</script>
</body>
</html>
update.jsp
技术分享图片
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User</title>
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/css/base.css">
</head>
<body>
<div class="content-body">
    <form class="layui-form" >

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>ID</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ readonly value=‘${user.id}‘>
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>账号</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ readonly value=‘${user.account}‘>
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>密码</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ readonly value=‘${user.password}‘>
          </div>
        </div>

        <div class=‘layui-form-item‘>
          <label class=‘layui-form-label‘>昵称</label>
          <div class=‘layui-input-block‘>
            <input type=‘text‘ class=‘layui-input‘ readonly value=‘${user.nickname}‘>
          </div>
        </div>
    </form>
</div>

</body>
</html>
detail.jsp

 

以上是关于自建生成代码工具(暂支持Spring boot +JPA)(更新中)的主要内容,如果未能解决你的问题,请参考以下文章

用户登录时的 Spring Boot 安全自定义消息

spring-boot-mybatis-plus-layui 自定义代码生成完整多对一

spring-boot-mybatis-plus-layui 自定义代码生成完整多对一

Spring Boot 自定义注解支持EL表达式(基于 MethodBasedEvaluationContext 实现)

Spring Boot中Spring MVC的整合支持

Spring boot 拾遗 —— Spring Cache 使用 Jackson 与 自定义 TTL