博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring mvc 实战化项目之三板斧
阅读量:6382 次
发布时间:2019-06-23

本文共 42320 字,大约阅读时间需要 141 分钟。

接上文希望从一张表(tb_role_info 用户角色表)的CRUD展开spring mvc的项目实战化魅力。

开发技术选型:spring mvc+freemarker+bootstrap+mybatis+mysql。

项目目录结构:

 (1)业务表 tb_role_info

-- ------------------------------ Table structure for `tb_role_info` 用户角色表-- ----------------------------DROP TABLE IF EXISTS `tb_role_info`;CREATE TABLE `tb_role_info` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `role_name` varchar(32) NOT NULL DEFAULT '' COMMENT '角色名称',  `role_mark` varchar(255) DEFAULT '' COMMENT '角色备注',  `creater_id` int(11) NOT NULL DEFAULT '0' COMMENT '记录创建者id',  `created_at` timestamp NULL DEFAULT NULL COMMENT '创建日期',  `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新日期',  `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间戳',  PRIMARY KEY (`id`),  KEY `tb_role_info_index` (`id`,`role_name`,`creater_id`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='角色信息表';

 

(2)业务界面 role.html

    <#include "header.html" />    
<#include "navbar.html" />
<#include "menu.html" />

角色信息

<#include "footer.html" />

 (3)业务界面逻辑 sys_role.js

/*** sys_role* 角色信息* @author steven9801@163.com* @date 2015-11-19*/(function ($) {    $(document).ready(function () {        /**        * 初始化        */        init();        /**        * 新建模态        */        $('#btn_role_add').click(function () {            addModal()        });        /**        * 编辑模态        */        $('#btn_role_edit').click(function () {            var rowList = dataGrid.bootstrapTable('getSelections');            var length = rowList.length;            if (length == 0) {                warningBox('请选择编辑对象.');                return false;            }            if (length > 1) {                warningBox('只能编辑一项.');                return false;            }            editModal(rowList[0]);        });        /**        * 保存动作        */        $('#btn_role_save').click(function () {            switch (dialogType) {                case 'add':                    onAdd();                    break;                case 'edit':                    onEdit();                    break;                default:                    break;            }        });        /**        * 删除        */        $('#btn_role_delete').click(function () {            onDelete();        });        //-----------------常规事件----------begin-------//        /**        * 刷新        */        $('#btn_role_refresh').click(function () {            dataGrid.bootstrapTable('destroy');            loadGrid();        });        /**        * 展开        */        $('#btn_search_expand').click(function () {            $(this).html('');            if(!searchStatus){                 $('#search_more_panel').show('slow');                 $(this).html('');                 searchStatus = true;             }             else{                 $('#search_more_panel').hide('slow');                 $(this).html('');                 searchStatus = false;             }             return false;        });        /**        * 提交查询        */        $('#btn_search_save').click(function () {            dataGrid.bootstrapTable('destroy');            bindGrid(function (params) {                var roleName = $('#search_txt_roleName').val();                role.pageSize = params.pageSize;                role.pageStart = params.pageSize * (params.pageNumber - 1);                role.sortName = params.sortName;                role.sortOrder = params.sortOrder;                if (roleName.length > 0) {                    role.roleName = roleName;                }                return JSON.stringify(role);            });        });        //-----------------常规事件----------end-------//    });})(jQuery);/*** 全局变量*///--------------------------全局变量区---------------------------//var dataGrid = null; //列表对象var dialogType = 'add';var role = {};var lock = false; //防止重复提交var searchStatus = false; //查询面板状态//--------------------------全局变量区---------------------------///*** 初始化*/function init() {    loadGrid();    $("#form_modal .modal-body").css({ height: "650px", overflowX: "hidden", overflowY: "auto" });    $('textarea.autosize').autosize({ append: "\n" });};/*** * 加载列表* */function loadGrid() {    bindGrid(function (params) {        return JSON.stringify({            pageSize: params.pageSize,            pageStart: params.pageSize * (params.pageNumber - 1),            sortName: params.sortName,            sortOrder: params.sortOrder        });    });    return false;};/*** 绑定列表*/function bindGrid(callBack) {    dataGrid = $('#role_table').bootstrapTable({        method: 'POST',        contentType: 'application/json;charset=utf-8',        url: '../admin/role',        height: 500,        striped: true,        pagination: true,        sidePagination: 'server',        pageSize: 25,        pageList: [25, 50, 100, 200],        showExport: true,        sortName: 'createdAt',        sortOrder: 'desc',        minimunCountColumns: 2,        formatLoadingMessage: function () {            return '';        },        queryParams: callBack,        columns:        [        { field: 'state', checkbox: true },        { field: 'roleName', title: '角色名称', align: 'left', valign: 'middle', sortable: true },        { field: 'createdAt', title: '创建时间', align: 'center', valign: 'middle', sortable: true },        { field: 'operate', title: '操作', align: 'left', valign: 'middle', sortable: false, formatter: operateFormatter, events: operateEvents }        ]    });};/*** 格式化操作列* */function operateFormatter(value, row, index) {    var content = [];    content.push(' ');    content.push(' ');    content.push(' ');    return content.join('');};/*** 操作列事件*/window.operateEvents = {    'click .view': function (e, value, row, index) {        viewModal(row);        return false;    },    'click .edit': function (e, value, row, index) {        editModal(row);        return false;    },    'click .delete': function (e, value, row, index) {        if (lock) return false;        lock = true;        if (userToken.id != row.createrId) {            lock = false;            warningBox('对不起,您无权删除该角色.');            return false;        }        var ids = [];        ids.push(row.id);        var params = {};        params.ids = ids;        deleteModal(params);    }};/*** 显示模态*/function showModal(action, title, width) {    dialogType = action;    $('.modal-footer').show();    $('#form_modal #form_modal_title').html(title);    $('#form_modal_dialog').css({ width: width });    $('select,textarea,input').prop('disabled', false);    $('#back-to-top').trigger('click');    return false;};/*** 绑定模态*/function bindModal(row) {    $('#form_hidden_id').val(row.id);    $('#form_hidden_createrId').val(row.createrId);    $('#form_txt_roleName').val(row.roleName);    $('#form_txt_roleMark').val(row.roleMark);    $("input[id^='power_']").removeAttr("checked");    var moduleIdList = row.moduleIdList;    for (var i in moduleIdList) {        var id = moduleIdList[i];        $("input[id='power_" + id + "']").prop("checked", true);    }};/*** 查看模态*/function viewModal(row) {    showModal('view', '角色查看', '60%');    bindModal(row);    $('select,textarea,input:not(.fixed-table-container input)').prop('disabled', true);    $('#search_panel select,#search_panel input').prop('disabled', false);    $('#table_tools_bar').find('input').prop('disabled', false);    $('.modal-footer').hide();    return false;};/*** 编辑模态*/function editModal(row) {    role = row;    if (userToken.id != row.createrId) {        pauseModal('#form_modal');        warningBox('对不起,您无权编辑该角色.');        return false;    }    showModal('edit', '角色编辑', '60%');    bindModal(row);    return false;};/*** 新建模态*/function addModal() {    showModal('add', '角色新建', '60%');    $('input[type=text],input[type=hidden],input[type=number],textarea').val('');    $('select option').eq(0).prop('selected', true);    $("input[id^='power_']").prop('checked', false);    return false;};/*** 验证表单*/function checkForm() {    if (lock) return false;    lock = true;    var roleName = $("#form_txt_roleName").val();    if (roleName.length == 0) {        warningBox("角色名称不能为空.");        lock = false;        return false;    }    if (roleName.length > 32) {        warningBox("角色名称最多32个字符.");        lock = false;        return false;    }    if ($("input[id^='power_']:checkbox:checked").length == 0) {        warningBox("请选择权限.");        lock = false;        return false;    }    var roleMark = $("#form_txt_roleMark").val();    if (roleMark.length > 255) {        warningBox("角色描述最多255个字符.");        lock = false;        return false;    }    var moduleIdList = [];    $("input[id^='power_']:checkbox:checked").each(function () {        var id = parseInt($(this).val());        moduleIdList.push(id);    });    role.roleName = roleName;    role.roleMark = roleMark;    role.moduleIdList = moduleIdList;    return true;};/*** 角色添加*/function onAdd() {    if (!checkForm()) {        return false;    }    $('.data-loading').show();    var task = new DelayedTask(function () {        $.ajax({            cache: false,            type: "POST",            dataType: "json",            contentType: "application/json;charset=utf-8",            url: "../admin/role.add",            data: JSON.stringify(role),            timeout: 30000,            success: function (data) {                if (data) {                    $(".data-loading").hide();                    var code = data.code;                    if (code != 0) {                        dangerBox(data.message);                        lock = false;                        return false;                    }                    lock = false;                    $('#form_modal').modal('hide')                    successBox('角色新建成功.');                    $('#btn_role_refresh').trigger('click');                }                return false;            },            error: function (e) {                if (e.status == 404) {                    window.location = "../404.html";                }                else if (e.status == 500) {                    window.location = "../500.html";                }            }        });    });    task.delay(500);    return false;};/*** 角色编辑*/function onEdit() {    if (!checkForm()) {        return false;    }    $('.data-loading').show();    var task = new DelayedTask(function () {        $.ajax({            cache: false,            type: "POST",            dataType: "json",            contentType: "application/json;charset=utf-8",            url: "../admin/role.edit",            data: JSON.stringify(role),            timeout: 30000,            success: function (data) {                if (data) {                    $(".data-loading").hide();                    var code = data.code;                    if (code != 0) {                        dangerBox(data.message);                        lock = false;                        return false;                    }                    lock = false;                    $('#form_modal').modal('hide')                    successBox('角色编辑成功.');                    $('#btn_role_refresh').trigger('click');                }                return false;            },            error: function (e) {                if (e.status == 404) {                    window.location = "../404.html";                }                else if (e.status == 500) {                    window.location = "../500.html";                }            }        });    });    task.delay(500);    return false;};/*** 角色删除*/function onDelete() {    if (lock) return false;    lock = true;    var ids = [];    var rowList = dataGrid.bootstrapTable('getSelections');    var length = rowList.length;    if (length == 0) {        warningBox('请选择删除对象.');        lock = false;        return false;    }    var flag = false;    for (var i in rowList) {        var row = rowList[i];        var createrId = row.createrId;        if (userToken.id != createrId) {            flag = true;        }        var id = row.id;        ids.push(id);    }    if (flag) {        warningBox('对不起,您无权删除该角色.');        lock = false;        return false;    }    var params = {};    params.ids = ids;    deleteModal(ids);    return false;};/*** 删除模态*/function deleteModal(ids) {    confirmBox('您确定要删除吗?!', function (result) {        if (result) {            $('.data-loading').show();            $.ajax({                cache: false,                type: 'POST',                dataType: 'json',                contentType: 'application/json;charset=utf-8',                url: '../admin/role.delete',                data: JSON.stringify(ids),                timeout: 30000,                success: function (data) {                    if (data) {                        $('.data-loading').hide();                        var code = data.code;                        if (code != 0) {                            dangerBox(data.message);                            lock = false;                            return false;                        }                        lock = false;                        successBox('角色删除成功.');                        $('#btn_role_refresh').trigger('click');                    }                    return false;                },                error: function (e) {                    if (e.status == 404) {                        window.location = '../404.html';                    }                    else if (e.status == 500) {                        window.location = '../500.html';                    }                }            });        }        else {            lock = false;        }    });    return false;};/*** 选择模块*/function checkModule(moduleId) {    $("input[name='fun_" + moduleId + "']").each(function () {        if ($(this).is(":checked") == true) {            $(this).prop("checked", false)        }        else {            $(this).prop("checked", true);        }    });};/*** 选择功能*/function checkFun(moduleId) {    var funLength = $("input[name='fun_" + moduleId + "']:checkbox:checked").length;    if (funLength != 0) {        $("input[name='mod_" + moduleId + "']").prop("checked", true);    }    else {        $("input[name='mod_" + moduleId + "']").prop("checked", false);    }};/*** 选择动作*/function checkAction(funId) {    var actLength = $("input[name='act_" + funId + "']:checkbox:checked").length;    if (actLength != 0) {        $("input[id='power_" + funId + "']").prop("checked", true);    }    else {        $("input[id='power_" + funId + "']").prop("checked", false);    }};

4)业务控制器 RoleController.java

package com.hwabao.controller;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;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.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.hwabao.common.CommanUtil;import com.hwabao.common.EntityGrid;import com.hwabao.common.SessionValidate;import com.hwabao.model.ModuleInfo;import com.hwabao.model.RoleInfo;import com.hwabao.model.RoleModule;import com.hwabao.model.UserInfo;import com.hwabao.service.IModuleInfoService;import com.hwabao.service.IRoleInfoService;import com.hwabao.service.IRoleModuleService;import com.hwabao.service.ITransactionalService;/** * * @ClassName: RoleController * @Description: 角色控制器* @author steven9801@163.com * @date 2015-4-21 下午04:36:24 * */@Controller@RequestMapping("/admin")public class RoleController extends BaseController{    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);        @Autowired    private HttpServletRequest request;    @Autowired    private IRoleInfoService roleInfoService;    @Autowired    private IModuleInfoService moduleInfoService;    @Autowired    private IRoleModuleService roleModuleService;    @Autowired    private ITransactionalService transactionalService;    /**     * 角色界面     */    @SessionValidate(comment="角色界面")    @RequestMapping(value = "/role", method = RequestMethod.GET)    public ModelAndView index() throws Exception    {        UserInfo user =  this.appContext.getCurrentUser(request);        if(user!=null)        {            ModelAndView mv = this.handlerModelView(user,"backend/role");            ModuleInfo model = new ModuleInfo();            model.moduleSortAsc();            List
list = moduleInfoService.selectModuleInfo(model); List
moduleList = this.toObjectModuleTree(list,0); mv.addObject("moduleList", moduleList); return mv; } return this.handlerModelView("backend/login"); } @SessionValidate(comment="角色列表") @RequestMapping(value = "/role", method = RequestMethod.POST) @ResponseBody public String grid(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { RoleInfo roleInfoModel = findRoleInfo(roleInfo); int total = roleInfoService.getRoleInfoSearchCount(roleInfoModel); List
roleList = roleInfoService.searchRoleInfo(roleInfoModel); EntityGrid
entityGrid = null; if(roleList!=null&&roleList.size()>0) { for(RoleInfo role:roleList) { List
moduleIdList = new ArrayList
(); RoleModule roleModule = new RoleModule(); roleModule.setRoleId(role.getId()); List
roleModuleList = roleModuleService.selectRoleModule(roleModule); for(RoleModule module:roleModuleList) { moduleIdList.add(module.getModuleId()); } role.setModuleIdList(moduleIdList); } entityGrid = new EntityGrid
(); entityGrid.rows = roleList; entityGrid.total = total; } else { entityGrid = new EntityGrid
(); } return this.handlerResponseMessage(entityGrid); } catch (Exception e) { logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色添加 */ @SessionValidate(comment="角色添加") @RequestMapping(value = "/role.add", method = RequestMethod.POST,consumes="application/json") @ResponseBody public String add(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { String roleName = roleInfo.getRoleName(); RoleInfo model = new RoleInfo(); model.setRoleName(roleName); RoleInfo cl = roleInfoService.getRoleInfo(model); if(cl!=null) { throw new Exception("角色名称重复."); } roleInfo.setCreatedAt(CommanUtil.getCurrentDatetime()); roleInfo.setCreaterId(user.getId()); int change = transactionalService.insertRoleInfo(roleInfo); if(change==0) { throw new Exception("角色新建失败."); } this.logSuccess("角色新建"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色新建"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色编辑 */ @SessionValidate(comment="角色编辑") @RequestMapping(value = "/role.edit", method = RequestMethod.POST,consumes="application/json") @ResponseBody public String edit(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { int change = transactionalService.updateRoleInfo(roleInfo); if(change==0) { throw new Exception("角色编辑失败."); } this.logSuccess("角色编辑"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色编辑"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色删除 */ @SessionValidate(comment="角色删除") @RequestMapping(value = "/role.delete",method = RequestMethod.POST,consumes="application/json") @ResponseBody public String delete(@RequestBody List
params) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { if(params.size()==0) { throw new Exception("params参数非空."); } List
roleList = new ArrayList
(); for(Integer roleid : params) { RoleInfo roleInfo = new RoleInfo(); roleInfo.setId(roleid); roleList.add(roleInfo); } int change = transactionalService.deleteRoleInfo((ArrayList
)roleList); if(change==0) { throw new Exception("角色删除失败."); } this.logSuccess("角色删除"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色删除"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 封装前端查询角色条件的方法 * @param roleInfo * @return */ private RoleInfo findRoleInfo(RoleInfo roleInfo) { if(roleInfo.getSortName()!=null&&roleInfo.getSortOrder()!=null) { String sortName = roleInfo.getSortName(); String sortOrder = roleInfo.getSortOrder(); roleInfo.setOrderBy(sortName, sortOrder); } if(roleInfo.getRoleName() != null) { roleInfo.roleNameLike(roleInfo.getRoleName()); } return roleInfo; } }

(5)业务实体层 RoleInfo.java

package com.hwabao.model;import java.util.List;import com.hwabao.common.VoBase;/** * @author steven9801@163.com */public class RoleInfo extends VoBase
{ private static final long serialVersionUID = 1L; /** * */ private Integer id; /** * 角色名称 */ private String roleName; /** * 角色备注 */ private String roleMark; /** * 记录创建者id */ private Integer createrId; /** * */ private String updatedAt; /** * */ private String createdAt; /** * 记录更新时间戳 */ private String timeStamp; //---------------------扩展属性-----------begin-----------// private List
moduleIdList; public List
getModuleIdList() { return moduleIdList; } public void setModuleIdList(List
moduleIdList) { this.moduleIdList = moduleIdList; } //---------------------扩展属性-----------end-----------// public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public void idDesc() { _setOrder("id", "DESC"); } public void idAsc() { _setOrder("id", "ASC"); } public void idMax(Integer max) { _setRangeMax("id", String.valueOf(max)); } public void idMin(Integer min) { _setRangeMin("id", String.valueOf(min)); } public void idEqual(boolean equal) { _setRangeEqual("id", equal); } public void idIn(Integer in) { _setIn("id", String.valueOf(in)); } public void idNotIn(Integer notin) { _setNotIn("id", String.valueOf(notin)); } public void idOr(Integer or) { _setOr("id", String.valueOf(or)); } public void idOrIn(Integer in) { _setOrIn("id", String.valueOf(in)); } public void idOrNotIn(Integer notin) { _setOrNotIn("id", String.valueOf(notin)); } public void idNull() { _setNull("id", null); } public void idNotNull(Integer nl) { _setNotNull("id", String.valueOf(nl)); } public String getRoleName() { return this.roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public void roleNameDesc() { _setOrder("roleName", "DESC"); } public void roleNameAsc() { _setOrder("roleName", "ASC"); } public void roleNameMax(String max) { _setRangeMax("roleName", max); } public void roleNameMin(String min) { _setRangeMin("roleName", min); } public void roleNameEqual(boolean equal) { _setRangeEqual("roleName", equal); } public void roleNameLike(String like) { _setLike("roleName", like); setRoleName(null); } public void roleNameOrLike(String like) { _setOrLike("roleName", like); setRoleName(null); } public void roleNameIn(String in) { _setIn("roleName", in); } public void roleNameNotIn(String notin) { _setNotIn("roleName", notin); } public void roleNameOr(String or) { _setOr("roleName", or); } public void roleNameOrIn(String in) { _setOrIn("roleName", in); } public void roleNameOrNotIn(String notin) { _setOrNotIn("roleName", notin); } public void roleNameNull() { _setNull("roleName", null); } public void roleNameNotNull(String nl) { _setNotNull("roleName", nl); } public String getRoleMark() { return this.roleMark; } public void setRoleMark(String roleMark) { this.roleMark = roleMark; } public void roleMarkDesc() { _setOrder("roleMark", "DESC"); } public void roleMarkAsc() { _setOrder("roleMark", "ASC"); } public void roleMarkMax(String max) { _setRangeMax("roleMark", max); } public void roleMarkMin(String min) { _setRangeMin("roleMark", min); } public void roleMarkEqual(boolean equal) { _setRangeEqual("roleMark", equal); } public void roleMarkLike(String like) { _setLike("roleMark", like); setRoleMark(null); } public void roleMarkOrLike(String like) { _setOrLike("roleMark", like); setRoleMark(null); } public void roleMarkIn(String in) { _setIn("roleMark", in); } public void roleMarkNotIn(String notin) { _setNotIn("roleMark", notin); } public void roleMarkOr(String or) { _setOr("roleMark", or); } public void roleMarkOrIn(String in) { _setOrIn("roleMark", in); } public void roleMarkOrNotIn(String notin) { _setOrNotIn("roleMark", notin); } public void roleMarkNull() { _setNull("roleMark", null); } public void roleMarkNotNull(String nl) { _setNotNull("roleMark", nl); } public Integer getCreaterId() { return this.createrId; } public void setCreaterId(Integer createrId) { this.createrId = createrId; } public void createrIdDesc() { _setOrder("createrId", "DESC"); } public void createrIdAsc() { _setOrder("createrId", "ASC"); } public void createrIdMax(Integer max) { _setRangeMax("createrId", String.valueOf(max)); } public void createrIdMin(Integer min) { _setRangeMin("createrId", String.valueOf(min)); } public void createrIdEqual(boolean equal) { _setRangeEqual("createrId", equal); } public void createrIdIn(Integer in) { _setIn("createrId", String.valueOf(in)); } public void createrIdNotIn(Integer notin) { _setNotIn("createrId", String.valueOf(notin)); } public void createrIdOr(Integer or) { _setOr("createrId", String.valueOf(or)); } public void createrIdOrIn(Integer in) { _setOrIn("createrId", String.valueOf(in)); } public void createrIdOrNotIn(Integer notin) { _setOrNotIn("createrId", String.valueOf(notin)); } public void createrIdNull() { _setNull("createrId", null); } public void createrIdNotNull(Integer nl) { _setNotNull("createrId", String.valueOf(nl)); } public String getUpdatedAt() { return this.updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public void updatedAtDesc() { _setOrder("updatedAt", "DESC"); } public void updatedAtAsc() { _setOrder("updatedAt", "ASC"); } public void updatedAtMax(String max) { _setRangeMax("updatedAt", max); } public void updatedAtMin(String min) { _setRangeMin("updatedAt", min); } public void updatedAtEqual(boolean equal) { _setRangeEqual("updatedAt", equal); } public void updatedAtLike(String like) { _setLike("updatedAt", like); setUpdatedAt(null); } public void updatedAtOrLike(String like) { _setOrLike("updatedAt", like); setUpdatedAt(null); } public void updatedAtIn(String in) { _setIn("updatedAt", in); } public void updatedAtNotIn(String notin) { _setNotIn("updatedAt", notin); } public void updatedAtOr(String or) { _setOr("updatedAt", or); } public void updatedAtOrIn(String in) { _setOrIn("updatedAt", in); } public void updatedAtOrNotIn(String notin) { _setOrNotIn("updatedAt", notin); } public void updatedAtNull() { _setNull("updatedAt", null); } public void updatedAtNotNull(String nl) { _setNotNull("updatedAt", nl); } public String getCreatedAt() { return this.createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public void createdAtDesc() { _setOrder("createdAt", "DESC"); } public void createdAtAsc() { _setOrder("createdAt", "ASC"); } public void createdAtMax(String max) { _setRangeMax("createdAt", max); } public void createdAtMin(String min) { _setRangeMin("createdAt", min); } public void createdAtEqual(boolean equal) { _setRangeEqual("createdAt", equal); } public void createdAtLike(String like) { _setLike("createdAt", like); setCreatedAt(null); } public void createdAtOrLike(String like) { _setOrLike("createdAt", like); setCreatedAt(null); } public void createdAtIn(String in) { _setIn("createdAt", in); } public void createdAtNotIn(String notin) { _setNotIn("createdAt", notin); } public void createdAtOr(String or) { _setOr("createdAt", or); } public void createdAtOrIn(String in) { _setOrIn("createdAt", in); } public void createdAtOrNotIn(String notin) { _setOrNotIn("createdAt", notin); } public void createdAtNull() { _setNull("createdAt", null); } public void createdAtNotNull(String nl) { _setNotNull("createdAt", nl); } public String getTimeStamp() { return this.timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public void timeStampDesc() { _setOrder("timeStamp", "DESC"); } public void timeStampAsc() { _setOrder("timeStamp", "ASC"); } public void timeStampMax(String max) { _setRangeMax("timeStamp", max); } public void timeStampMin(String min) { _setRangeMin("timeStamp", min); } public void timeStampEqual(boolean equal) { _setRangeEqual("timeStamp", equal); } public void timeStampLike(String like) { _setLike("timeStamp", like); setTimeStamp(null); } public void timeStampOrLike(String like) { _setOrLike("timeStamp", like); setTimeStamp(null); } public void timeStampIn(String in) { _setIn("timeStamp", in); } public void timeStampNotIn(String notin) { _setNotIn("timeStamp", notin); } public void timeStampOr(String or) { _setOr("timeStamp", or); } public void timeStampOrIn(String in) { _setOrIn("timeStamp", in); } public void timeStampOrNotIn(String notin) { _setOrNotIn("timeStamp", notin); } public void timeStampNull() { _setNull("timeStamp", null); } public void timeStampNotNull(String nl) { _setNotNull("timeStamp", nl); } public String _getPrimary() { return String.valueOf(id); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{\n"); sb.append(" id:" + getId() + ",\n"); sb.append(" role_name:" + _getSnap(getRoleName()) + ",\n"); sb.append(" role_mark:" + _getSnap(getRoleMark()) + ",\n"); sb.append(" creater_id:" + getCreaterId() + ",\n"); sb.append(" updated_at:" + _getSnap(getUpdatedAt()) + ",\n"); sb.append(" created_at:" + _getSnap(getCreatedAt()) + ",\n"); sb.append(" time_stamp:" + _getSnap(getTimeStamp()) + "\n"); sb.append("}\n"); return sb.toString(); } public void setOrderBy(String sortName,String sortOrder){ if(sortOrder.equalsIgnoreCase("asc")){ if(sortName.equalsIgnoreCase("id")){ idAsc(); } if(sortName.equalsIgnoreCase("roleName")){ roleNameAsc(); } if(sortName.equalsIgnoreCase("roleMark")){ roleMarkAsc(); } if(sortName.equalsIgnoreCase("createrId")){ createrIdAsc(); } if(sortName.equalsIgnoreCase("updatedAt")){ updatedAtAsc(); } if(sortName.equalsIgnoreCase("createdAt")){ createdAtAsc(); } if(sortName.equalsIgnoreCase("timeStamp")){ timeStampAsc(); } } else if(sortOrder.equalsIgnoreCase("desc")){ if(sortName.equalsIgnoreCase("id")){ idDesc(); } if(sortName.equalsIgnoreCase("roleName")){ roleNameDesc(); } if(sortName.equalsIgnoreCase("roleMark")){ roleMarkDesc(); } if(sortName.equalsIgnoreCase("createrId")){ createrIdDesc(); } if(sortName.equalsIgnoreCase("updatedAt")){ updatedAtDesc(); } if(sortName.equalsIgnoreCase("createdAt")){ createdAtDesc(); } if(sortName.equalsIgnoreCase("timeStamp")){ timeStampDesc(); } }} public boolean equals(Object o) { if (o instanceof RoleInfo) { RoleInfo roleInfo = (RoleInfo) o; return roleInfo.getId().equals(getId()) && roleInfo.getRoleName().equals(getRoleName()) && roleInfo.getRoleMark().equals(getRoleMark()) && roleInfo.getCreaterId().equals(getCreaterId()) && roleInfo.getUpdatedAt().equals(getUpdatedAt()) && roleInfo.getCreatedAt().equals(getCreatedAt()) && roleInfo.getTimeStamp().equals(getTimeStamp()); } return false; }}

(6)业务数据层 IRoleInfoData.java

package com.hwabao.data;import java.util.List;import java.util.ArrayList;import com.hwabao.model.RoleInfo;import com.hwabao.common.Pager;/** * @author steven9801@163.com */public interface IRoleInfoData {    public int insertRoleInfo(RoleInfo roleInfo);    public int updateRoleInfo(RoleInfo roleInfo);    public int deleteRoleInfo(RoleInfo roleInfo);    public RoleInfo getRoleInfo(RoleInfo roleInfo);    public int getRoleInfoCount(RoleInfo roleInfo);    public List
selectRoleInfo(RoleInfo roleInfo); public List
selectRoleInfo(RoleInfo roleInfo, Pager pager); public List
selectRoleInfoByList(ArrayList
arrListId); public int getRoleInfoSearchCount(RoleInfo roleInfo); public List
searchRoleInfo(RoleInfo roleInfo); public List
searchRoleInfo(RoleInfo roleInfo, Pager pager);}

(7)业务服务层 RoleInfoService.java

package com.hwabao.service.impl;import java.util.List;import java.util.ArrayList;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.hwabao.data.IRoleInfoData;import com.hwabao.model.RoleInfo;import com.hwabao.service.IRoleInfoService;import com.hwabao.common.Pager;/** * @author steven9801@163.com */@Servicepublic class RoleInfoService implements IRoleInfoService {    @Autowired    private IRoleInfoData roleInfoData;    @Override    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })    public int insertRoleInfo(RoleInfo roleInfo) {        return roleInfoData.insertRoleInfo(roleInfo);    }    @Override    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })    public int insertRoleInfoBatch(ArrayList
arrListRoleInfo) { int insertedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.insertRoleInfo(roleInfo); if (result < 1) { return 0; } insertedCount++; } return insertedCount; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int updateRoleInfo(RoleInfo roleInfo) { return roleInfoData.updateRoleInfo(roleInfo); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int updateRoleInfoBatch(ArrayList
arrListRoleInfo) { int updatedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.updateRoleInfo(roleInfo); if (result < 1) { return 0; } updatedCount++; } return updatedCount; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int deleteRoleInfo(RoleInfo roleInfo) { return roleInfoData.deleteRoleInfo(roleInfo); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int deleteRoleInfoBatch(ArrayList
arrListRoleInfo) { int deletedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.deleteRoleInfo(roleInfo); if (result < 1) { return 0; } deletedCount++; } return deletedCount; } @Override public RoleInfo getRoleInfo(RoleInfo roleInfo) { return roleInfoData.getRoleInfo(roleInfo); } @Override public RoleInfo getRoleInfo(Integer id) { RoleInfo roleInfo = new RoleInfo(); roleInfo.setId(id); return getRoleInfo(roleInfo); } @Override public int getRoleInfoCount(RoleInfo roleInfo) { return roleInfoData.getRoleInfoCount(roleInfo); } @Override public List
selectRoleInfo(RoleInfo roleInfo) { return roleInfoData.selectRoleInfo(roleInfo); } @Override public List
selectRoleInfo(RoleInfo roleInfo, Pager pager) { if (null != pager) { int count = roleInfoData.getRoleInfoCount(roleInfo); if (count == 0) { return null; } pager.setRowCount(count); } return roleInfoData.selectRoleInfo(roleInfo, pager); } @Override public List
selectRoleInfoByList(ArrayList
arrListId) { if (arrListId.size() == 0) { return null; } return roleInfoData.selectRoleInfoByList(arrListId); } @Override public int getRoleInfoSearchCount(RoleInfo roleInfo) { return roleInfoData.getRoleInfoSearchCount(roleInfo); } @Override public List
searchRoleInfo(RoleInfo roleInfo) { return roleInfoData.searchRoleInfo(roleInfo); } @Override public List
searchRoleInfo(RoleInfo roleInfo, Pager pager) { if (null != pager) { int count = roleInfoData.getRoleInfoSearchCount(roleInfo); if (count == 0) { return null; } pager.setRowCount(count); } return roleInfoData.searchRoleInfo(roleInfo, pager); }}
package com.hwabao.service;import java.util.List;import java.util.ArrayList;import com.hwabao.model.RoleInfo;import com.hwabao.common.Pager;/** * @author steven9801@163.com */public interface IRoleInfoService {    public int insertRoleInfo(RoleInfo roleInfo);    public int insertRoleInfoBatch(ArrayList
arrListRoleInfo); public int updateRoleInfo(RoleInfo roleInfo); public int updateRoleInfoBatch(ArrayList
arrListRoleInfo); public int deleteRoleInfo(RoleInfo roleInfo); public int deleteRoleInfoBatch(ArrayList
arrListRoleInfo); public RoleInfo getRoleInfo(RoleInfo roleInfo); public RoleInfo getRoleInfo(Integer id); public int getRoleInfoCount(RoleInfo roleInfo); public List
selectRoleInfo(RoleInfo roleInfo); public List
selectRoleInfo(RoleInfo roleInfo, Pager pager); public List
selectRoleInfoByList(ArrayList
arrListId); public int getRoleInfoSearchCount(RoleInfo roleInfo); public List
searchRoleInfo(RoleInfo roleInfo); public List
searchRoleInfo(RoleInfo roleInfo, Pager pager);}

就这样简单整个业务表的CRUD结构清晰的完整的呈现在你面前啦。管中窥豹,真正拥有者会如获至宝。

敬请期待下期:

asp.net mvc 实战化项目之三板斧

感兴趣的朋友扫下面的二维码给点打赏吧!

                  

转载地址:http://trwha.baihongyu.com/

你可能感兴趣的文章
Java 获取文件的上级目录
查看>>
Confluence 6 CSS 编辑快速入门
查看>>
我要做 Android 之消息机制
查看>>
极简的高性能框架 one 1.4.6 发布,新增参数验证器
查看>>
推荐两个漂亮的编程字体
查看>>
Linux系统诊断小技巧(14):启停问题之如何修复initrd损坏
查看>>
Python数据科学分析速查表
查看>>
jmeter测试教程
查看>>
Trie 树内存消耗问题
查看>>
区块链教程btcpool矿池源码分析slparser
查看>>
OC 中,覆盖属性会有怎么样的化学反应?
查看>>
Linux MySQL 8.0 忘记密码
查看>>
Android:随笔——我们用什么来替代 Enum 这个内存大户
查看>>
TCP连接的状态详解以及故障排查
查看>>
RFC2616-HTTP1.1-Methods(方法规定部分—译文)
查看>>
集成学习之Boosting —— Gradient Boosting原理
查看>>
linux常见一级目录的用途
查看>>
Linux epoll模型详解及源码分析
查看>>
scala 类似 Python join 的方法
查看>>
Hadoop 2.6.0集群搭建
查看>>