自建生成代码工具(暂支持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"></i>
                    </a>
                    <a class="layui-btn layui-btn-sm btn-update">
                        <i class="layui-icon"></i>
                    </a>
                    <a class="layui-btn layui-btn-sm btn-delete">
                        <i class="layui-icon"></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

原文地址:https://www.cnblogs.com/markdev/p/8986777.html

时间: 2024-11-05 20:29:50

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

Spring Boot 持续更新中...

内容 Spring Boot入门 Spring Boot配置 Spring Boot与日志 Spring Boot与Web开发 Spring Boot与Docker Spring Boot与数据访问 Spring Boot启动配置原理 Spring Boot自定义starters Spring Boot与缓存 Spring Boot与消息 Spring Boot与检索 Spring Boot与任务 Spring Boot与安全 Spring Boot与分布式 Spring Boot与开发热部署

mybatis generator生成代码工具的使用

mybatis generator生成代码工具的使用, 附demo 使用Hibernate时, 可以很方便的生成model,dao,和映射配置文件.在mybatis里, 也有生成器, 即mybatis generator, 简称MBG. 下面为大家介绍一下MBG的使用. 下载mybatis-generator-core-1.3.1-bundle.zip之后, 解压得到mybatis-generator-core-1.3.1.jar, 即生成器的jar包, 将mybatis-3.0.6.jar和m

懒人css3样式代码生成器-一款懒人的样式生成代码工具

原文:懒人css3样式代码生成器-一款懒人的样式生成代码工具 源代码下载地址:http://www.zuidaima.com/share/1607130326682624.htm 版权声明:本文为博主原创文章,未经博主允许不得转载.

代码大爆炸|用Spring Boot创建微服务的21种代码描述(上)

代码大爆炸|用Spring Boot创建微服务的21种代码描述(上)

Spring Boot Jpa 的使用

使用 Spring Boot Jpa 开发时,发现国内对 Spring Boot Jpa 全面介绍的文章比较少案例也比较零碎,因此写文章总结一下Spring Data JPA 参考指南! Spring Boot Jpa 介绍 首先了解 Jpa 是什么? Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范.它为 Java 开发人员提供了一种对象/关联映射工具来管理 Java 应用中的关系数据.它的出现主要是为了简化现有的持久化开发工作和整合 ORM

Spring Boot源码中模块详解

Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1.x 二.模块 Spring Boot 包含许多模块,以下是一些简单的概述: 1,spring-boot 为Spring Boot其他部分功能提供主要的lib包,其中包含:(1)SpringApplication类提供了静态便利的方法使编写独立的SpringApplication更加容易.它唯一的任

Spring Boot JPA 连接数据库

本文将介绍如何在Spring Boot 工程中添加JPA作为持久化方式. 修改 pom.xml 依赖 与上一篇介绍的 jdbc 不同的是 spring-boot-starter-jdbc 修改为 spring-boot-starter-data-jpa 即可,当然数据库驱动包也是不可少的,如下: <!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-conne

Spring Boot + JPA 多模块项目无法注入 JpaRepository 接口

问题描述 Spring Boot + JPA 多模块项目,启动报异常: nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '***.***.***Dao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency

自制Https证书并在Spring Boot和Nginx中使用(转)

白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环境中服务器端的配置. 如果你还没有读过白话Https,我强烈建议你先去读一下.按照白话Https中的介绍,Https协议涉及到的主体主要有三个:客户端.服务端.以及CA机构.如下图所示: 在白话Https一文中,曾介绍一个服务要申请使用Https的流程.本文所介绍的流程,针对自制Https证书,更多