FEBS框架增删查改教程

下面将用一个网段的增删查改为例子介绍FEBS框架开发。建表语句如下:

–vlan管理———–开始————

CREATE SEQUENCE “IPAM”.”SEQ_VLAN”

 INCREMENT BY 1

 MINVALUE 1

 MAXVALUE 9999999999999999999999999999

 START WITH 200

 CACHE 20;

CREATE TABLE “IPAM”.”T_VLAN” (

“VLAN_ID” NUMBER NOT NULL ,

“SHOWORDER” NUMBER,

“DATATYPE” NUMBER,

“CREATE_TIME” DATE NOT NULL ,

“MODIFY_TIME” DATE ,

“MODIFY_BY” VARCHAR2(100 BYTE),

“VLAN_NAME” VARCHAR2(20) NOT NULL

)

LOGGING

NOCOMPRESS

NOCACHE             

;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”IP_VLAN” IS ‘主键GUID’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”SHOWORDER” IS ‘排序字段’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”DATATYPE” IS ‘数据是否可用1可用0不可用’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”CREATE_TIME” IS ‘创建时间’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”MODIFY_TIME” IS ‘修改时间’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”MODIFY_BY” IS ‘修改人’;

COMMENT ON COLUMN “IPAM”.”T_VLAN”.”VLAN_NAME” IS ‘VLAN名称’;

–vlan管理———–结束————

直接复制到数据库执行。

二、导入FEBS项目

1.在eclipse左侧右键,选择菜单import

2.选择Existing Maven Projects 然后点击Next

3.选择从gitblit上克隆下来的项目。打勾/pom.xml并点击Finish

4.导入成功后项目结构如下。

src/main/java 存放java代码

src/main/resources 存放配置文件和静态文件

三、代码的自动生成

由于FEBS使用的是Mybatis作为持久层框架,所以可以使用Mybatis的自动生成的特性,生成相应的

代码生成配置文件位于resources/config/mybatis-generator.xml:只需要配置需要生成的表的tableName和domainObjectName属性即可。由于本例的表名(tableName)为T_VLAN,实体(domainObjectName)为VLAN所以做对应的修改。generatedKey的column属性修改为VLAN_ID

        <!– 配置需要生成的表 –>

        <table tableName=“T_VLAN” domainObjectName=“VLAN” enableCountByExample=“false” enableUpdateByExample=“false” enableDeleteByExample=“false” enableSelectByExample=“false” selectByExampleQueryId=“false”>

            <generatedKey column=VLAN_ID” sqlStatement=“oralce” identity=“true”/>

        </table>

配置好该文件后,找到pom.xml中如下插件,将其注释去掉启用:

<plugin>

            <groupId>org.mybatis.generator</groupId>

            <artifactId>mybatis-generator-maven-plugin</artifactId>

            <version>1.3.5</version>

            <dependencies>

                <dependency>

    <groupId>cn.easyproject</groupId>

    <artifactId>ojdbc6</artifactId>

    <version>12.1.0.2.0</version>

</dependency>

                <dependency>

                    <groupId>tk.mybatis</groupId>

                    <artifactId>mapper</artifactId>

                    <version>3.4.0</version>

                </dependency>

            </dependencies>

            <executions>

                <execution>

                    <id>Generate MyBatis Artifacts</id>

                    <phase>package</phase>

                    <goals>

                        <goal>generate</goal>

                    </goals>

                </execution>

            </executions>

            <configuration>

                <verbose>true</verbose>

                <overwrite>true</overwrite>

                <configurationFile>src/main/resources/config/mybatis-generator.xml</configurationFile>

            </configuration>

        </plugin>

保存pom.xml后运行启动项目:

右键project->Run As->Maven install

打开项目可以看到

在src/main/java下,已经生成了

cc.mrbird.system.dao. VLANMapper.java

cc.mrbird.system.domain. VLAN.java

在scr/main/resources/mapper/system下,已经生成了

VLANMapper.xml

生成的代码如下所示:

VLANMapper.java

VLAN.java

  • VLANMapper.xml
  • 代码生成后,最好将pom.xml中刚刚开启的插件重新注释掉。因为在项目打包的时候会自动运行该插件,这样如果生成的代码后续有修改的话,将会被覆盖掉。所以通常的做法是只有在需要生成代码的时候才将该插件开启。

四、修改java代码

1.修改自动生成的代码

VLANMapper.java    VLANMapper.xml

这两个文件不用做任何修改

VLAN.java需要做如下修改

  1. 实现序列化借口
  2. 添加一个SEQ属性,属性值为在Oracle中建表时创建的序列,大小写不敏感。
  3. 代码自动生成的数值类型是Short,这里将所有的Short替换为Long
  4. 删除vlanId头上的注解,@GeneratedValue(strategy = GenerationType.IDENTITY)

该注解用于mysql自动生成自增型数值主键,oracle只用使用Sequence 自增序列

  • @ExportConfig注解是到处excel需要用到的在excel中显示的表头名称

 2.在cc.mrbird.system.service包下新建接口类VLANService.java

VLANService.java代码如下。

3.在包 cc.mrbird.system.service.impl包下新建刚才创建的接口类的实现类

具体代码如下:

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;

import tk.mybatis.mapper.entity.Example.Criteria;

import cc.mrbird.common.service.impl.BaseService;

import cc.mrbird.system.domain.VLAN;

import cc.mrbird.system.service.VLANService;

@Service(“VLANService”)

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)

public class VLANServiceImpl extends BaseService<VLAN> implements VLANService{

@Override

public List<VLAN> findAllVLANs(VLAN vlan) {

try {

Example example = new Example(VLAN.class);

Criteria criteria = example.createCriteria();

if (StringUtils.isNotBlank(vlan.getVlanName())) {

criteria.andCondition(“VLAN_NAME LIKE”, “%”+ vlan.getVlanName() + “%”);

}

example.setOrderByClause(“CREATE_TIME DESC”);

return this.selectByExample(example);

} catch (NumberFormatException e) {

e.printStackTrace();

return new ArrayList<>();

}

}

@Override

public VLAN findById(Long vlanId) {

return this.selectByKey(vlanId);

}

@Override

public void addVLAN(VLAN vlan) {

vlan.setVlanId(this.getSequence(vlan.SEQ));

this.save(vlan);

}

@Override

public void deleteVLANs(String vlanIds) {

List<String> list = Arrays.asList(vlanIds.split(“,”));

this.batchDelete(list, “vlanId”, VLAN.class);

}

@Override

@Transactional

public void updateVLAN(VLAN vlan) {

this.updateNotNull(vlan);

}

}

4.在cc.mrbird.system.controller包中创建控制器类VLANController.java,代码如下

package cc.mrbird.system.controller;

import java.util.Date;

import java.util.List;

import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;

import cc.mrbird.common.annotation.Log;

import cc.mrbird.common.controller.BaseController;

import cc.mrbird.common.domain.QueryRequest;

import cc.mrbird.common.domain.ResponseBo;

import cc.mrbird.common.util.FileUtils;

import cc.mrbird.system.domain.VLAN;

import cc.mrbird.system.domain.User;

import cc.mrbird.system.service.VLANService;

@Controller

public class VLANController extends BaseController {

@Autowired

private VLANService vlanService;

@Log(“获取网段信息”)

@RequestMapping(“vlan”)

@RequiresPermissions(“vlan:list”)

public String index() {

return “system/vlan/vlan”;

}

@RequestMapping(“vlan/list”)

@ResponseBody

public Map<String, Object> vlanList(QueryRequest request, VLAN vlan) {

PageHelper.startPage(request.getPageNum(), request.getPageSize());

List<VLAN> list = this.vlanService.findAllVLANs(vlan);

PageInfo<VLAN> pageInfo = new PageInfo<>(list);

return getDataTable(pageInfo);

}

@RequestMapping(“vlan/excel”)

@ResponseBody

public ResponseBo vlanExcel(VLAN vlan) {

try {

List<VLAN> list = this.vlanService.findAllVLANs(vlan);

return FileUtils.createExcelByPOIKit(“网段列表”, list, VLAN.class);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“导出Excel失败,请联系网站管理员!”);

}

}

@RequestMapping(“vlan/csv”)

@ResponseBody

public ResponseBo vlanCsv(VLAN vlan){

try {

List<VLAN> list = this.vlanService.findAllVLANs(vlan);

return FileUtils.createCsv(“网段列表”, list, VLAN.class);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“导出Csv失败,请联系网站管理员!”);

}

}

@RequestMapping(“vlan/getVlan”)

@ResponseBody

public ResponseBo getVLAN(Long vlanId) {

try {

VLAN vlan = this.vlanService.findById(vlanId);

return ResponseBo.ok(vlan);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“获取vlan失败,请联系网站管理员!”);

}

}

@Log(“新增vlan地址 “)

@RequiresPermissions(“vlan:add”)

@RequestMapping(“vlan/add”)

@ResponseBody

public ResponseBo addVLAN(VLAN vlan) {

try {

vlan.setCreateTime(new Date());

this.vlanService.addVLAN(vlan);

return ResponseBo.ok(“新增vlan地址成功!”);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“新增vlan地址失败,请联系网站管理员!”);

}

}

@Log(“删除vlan地址”)

@RequiresPermissions(“vlan:delete”)

@RequestMapping(“vlan/delete”)

@ResponseBody

public ResponseBo deleteVLANs(String ids) {

try {

this.vlanService.deleteVLANs(ids);

return ResponseBo.ok(“删除vlan地址成功!”);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“删除vlan地址失败,请联系网站管理员!”);

}

}

@Log(“修改vlan地址 “)

@RequiresPermissions(“vlan:update”)

@RequestMapping(“vlan/update”)

@ResponseBody

public ResponseBo updateVLAN(VLAN vlan) {

try {

User user = super.getCurrentUser();

vlan.setModifyTime(new Date());

vlan.setModifyBy(user.getUsername());

this.vlanService.updateVLAN(vlan);

return ResponseBo.ok(“修改vlan地址成功!”);

} catch (Exception e) {

e.printStackTrace();

return ResponseBo.error(“修改vlan地址失败,请联系网站管理员!”);

}

}

}

五、修改页面

在src/main/resources/templates/system下 新建文件目录vlan,在vlan目录下分别创建vlan.html和vlanAdd.html

vlan.html代码如下

<div data-th-include=“system/vlan/vlanAdd”></div>

<div class=“card”>

    <div class=“card-block”>

        <div class=“table-responsive”>

            <div id=“data-table_wrapper” class=“dataTables_wrapper”>

                <div class=“dataTables_buttons hidden-sm-down actions”>

                    <span class=“actions__item zmdi zmdi-search” onclick=”search()” title=“搜索” />

                    <span class=“actions__item zmdi zmdi-refresh-alt” onclick=”refresh()” title=“刷新” />

                    <div class=“dropdown actions__item”>

                        <i data-toggle=“dropdown” class=“zmdi zmdi-download”>

            </i>

                        <ul class=“dropdown-menu dropdown-menu-right”>

                            <a href=“javascript:void(0)” class=“dropdown-item” data-table-action=“excel” onclick=”exportIpExcel()”>

                    Excel (.xlsx)

                </a>

                            <a href=“javascript:void(0)” class=“dropdown-item” data-table-action=“csv” onclick=”exportIpCsv()”>

                    CSV (.csv)

                </a>

                        </ul>

                    </div>

                    <div class=“dropdown actions__item” shiro:hasAnyPermissions=“vlan:add,vlan:update,vlan:delete”>

                        <i data-toggle=“dropdown” class=“zmdi zmdi-more-vert”></i>

                        <div class=“dropdown-menu dropdown-menu-right”>

                            <a href=“javascript:void(0)” class=“dropdown-item” data-toggle=“modal” data-target=“#vlan-add” shiro:hasPermission=“vlan:add”>新增vlan</a>

                            <a href=“javascript:void(0)” class=“dropdown-item” onclick=”updateIp()” shiro:hasPermission=“vlan:update”>修改vlan</a>

                            <a href=“javascript:void(0)” class=“dropdown-item” onclick=”deleteIps()” shiro:hasPermission=“vlan:delete”>删除vlan</a>

                        </div>

                    </div>

                </div>

                <div id=“data-table_filter” class=“dataTables_filter”>

                    <form class=“vlan-table-form”>

                        <div class=“row”>

                            <div class=“col-sm-3”>

                                <div class=“input-group”>

                                    <span class=“input-group-addon”>

                vlan:

            </span>

                                    <div class=“form-group”>

                                        <input type=“text” name=“vlan” class=“form-control”>

                                        <i class=“form-group__bar”></i>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </form>

                </div>

                <div class=“table-responsive”>

                    <table id=“vlanTable” data-mobile-responsive=“true” class=“mb-bootstrap-table text-nowrap”></table>

                </div>

            </div>

        </div>

    </div>

</div>

<script data-th-src=“@{js/app/system/vlan/vlan.js}”></script>

<script data-th-src=“@{js/app/system/vlan/vlanEdit.js}”></script>

vlanAdd.html代码如下

<div class=“modal fade” id=“vlan-add” data-keyboard=“false” data-backdrop=“static” tabindex=“-1”>

    <div class=“modal-dialog modal-lg”>

        <div class=“modal-content”>

            <div class=“modal-header”>

                <h3 class=“modal-title pull-left” id=“vlan-add-modal-title”>新增vlan</h3>

            </div>

            <div class=“modal-body”>

                <form id=“vlan-add-form”>

                    <div class=“row”>

                        <div class=“col-sm-11”>

                            <div class=“input-group”>

                                <span class=“input-group-addon”>

                vlan:

            </span>

                                <div class=“form-group”>

                                    <input type=“text” name=“vlanAddress” class=“form-control”>

                                    <input type=“text” name=“vlanId” hidden class=“form-control”>

                                </div>

                            </div>

                        </div>

                    </div>

                </form>

            </div>

            <div class=“modal-footer”>

                <button type=“button” class=“btn btn-save” id=“vlan-add-button” name=“save”>保存</button>

                <button type=“button” class=“btn btn-secondary btn-close”>关闭</button>

                <button class=“btn-hide”></button>

            </div>

        </div>

    </div>

</div>

<script data-th-src=“@{js/app/system/vlan/vlanAdd.js}”></script>

六、修改JS代码

在src/main/resources/static/js/app/system目录下创建vlan目录,并分别创建vlan.js vlanAdd.js和vlanEdit.js三个js文件

vlan.js代码如下:

$(function() {

    var $vlanTableForm = $(“.vlan-table-form”);

    var settings = {

        url: ctx + “vlan/list”,

        pageSize: 10,

        queryParams: function(params) {

            return {

                pageSize: params.limit,

                pageNum: params.offset / params.limit + 1,

                vlanName: $vlanTableForm.find(“input[name=’vlanName’]”).val().trim()

            };

        },

        columns: [{

                checkbox: true

            },

            {

                field: ‘vlanId’,

                title: ‘序号’,

                width: 150

            }, {

                field: ‘vlanName’,

                title: ‘网段’

            }

        ]

    };

    $MB.initTable(‘vlanTable’, settings);

});

function search() {

    $MB.refreshTable(‘vlanTable’);

}

function refresh() {

    $(“.vlan-table-form”)[0].reset();

    search();

}

function deleteVlans() {

    var selected = $(“#vlanTable”).bootstrapTable(‘getSelections’);

    var selected_length = selected.length;

    if (!selected_length) {

        $MB.n_warning(‘请勾选需要删除的网关!’);

        return;

    }

    var ids = “”;

    for (var i = 0; i < selected_length; i++) {

        ids += selected[i].vlanId;

        if (i !== (selected_length – 1)) ids += “,”;

    }

    $MB.confirm({

        text: “确定删除选中的网关?”,

        confirmButtonText: “确定删除”

    }, function() {

        $.post(ctx + ‘vlan/delete’, { “ids”: ids }, function(r) {

            if (r.code === 0) {

                $MB.n_success(r.msg);

                refresh();

            } else {

                $MB.n_danger(r.msg);

            }

        });

    });

}

function exportIpExcel(){

$.post(ctx+”vlan/excel”,$(“.vlan-table-form”).serialize(),function(r){

if (r.code === 0) {

window.location.href = “common/download?fileName=” + r.msg + “&delete=” + true;

} else {

$MB.n_warning(r.msg);

}

});

}

function exportIpCsv(){

$.post(ctx+”vlan/csv”,$(“.vlan-table-form”).serialize(),function(r){

if (r.code === 0) {

window.location.href = “common/download?fileName=” + r.msg + “&delete=” + true;

} else {

$MB.n_warning(r.msg);

}

});

}

vlanAdd.js代码如下

var validator;

var $vlanAddForm = $(“#vlan-add-form”);

$(function () {

    validateRule();

    $(“#vlan-add .btn-save”).click(function () {

        var name = $(this).attr(“name”);

        validator = $vlanAddForm.validate();

        var flag = validator.form();

        if (flag) {

            if (name === “save”) {

                $.post(ctx + “vlan/add”, $vlanAddForm.serialize(), function (r) {

                    if (r.code === 0) {

                        closeModal();

                        refresh();

                        $MB.n_success(r.msg);

                    } else $MB.n_danger(r.msg);

                });

            }

            if (name === “update”) {

                $.post(ctx + “vlan/update”, $vlanAddForm.serialize(), function (r) {

                    if (r.code === 0) {

                        closeModal();

                        refresh();

                        $MB.n_success(r.msg);

                    } else $MB.n_danger(r.msg);

                });

            }

        }

    });

    $(“#vlan-add .btn-close”).click(function () {

        closeModal();

    });

});

function closeModal() {

    $(“#vlan-add-button”).attr(“name”, “save”);

    $(“#vlan-add-modal-title”).html(‘新增网段’);

    validator.resetForm();

    $MB.closeAndRestModal(“vlan-add”);

}

function validateRule() {

    var icon = “<i class=’zmdi zmdi-close-circle zmdi-hc-fw’></i> “;

    validator = $vlanAddForm.validate({

        rules: {

         vlanAddress: {

                required: true,

                maxlength: 15

            }

        },

        messages: {

         vlanAddress: {

                required: icon + “请输入网段”,

                maxlength: icon + “长度不能超过15个字符”

            }

        }

    });

}

vlanEdit.js代码如下

$(function() {

    var $vlanTableForm = $(“.vlan-table-form”);

    var settings = {

        url: ctx + “vlan/list”,

        pageSize: 10,

        queryParams: function(params) {

            return {

                pageSize: params.limit,

                pageNum: params.offset / params.limit + 1,

                vlanName: $vlanTableForm.find(“input[name=’vlanName’]”).val().trim()

            };

        },

        columns: [{

                checkbox: true

            },

            {

                field: ‘vlanId’,

                title: ‘序号’,

                width: 150

            }, {

                field: ‘vlanName’,

                title: ‘网段’

            }

        ]

    };

    $MB.initTable(‘vlanTable’, settings);

});

function search() {

    $MB.refreshTable(‘vlanTable’);

}

function refresh() {

    $(“.vlan-table-form”)[0].reset();

    search();

}

function deleteVlans() {

    var selected = $(“#vlanTable”).bootstrapTable(‘getSelections’);

    var selected_length = selected.length;

    if (!selected_length) {

        $MB.n_warning(‘请勾选需要删除的网关!’);

        return;

    }

    var ids = “”;

    for (var i = 0; i < selected_length; i++) {

        ids += selected[i].vlanId;

        if (i !== (selected_length – 1)) ids += “,”;

    }

    $MB.confirm({

        text: “确定删除选中的网关?”,

        confirmButtonText: “确定删除”

    }, function() {

        $.post(ctx + ‘vlan/delete’, { “ids”: ids }, function(r) {

            if (r.code === 0) {

                $MB.n_success(r.msg);

                refresh();

            } else {

                $MB.n_danger(r.msg);

            }

        });

    });

}

function exportIpExcel(){

$.post(ctx+”vlan/excel”,$(“.vlan-table-form”).serialize(),function(r){

if (r.code === 0) {

window.location.href = “common/download?fileName=” + r.msg + “&delete=” + true;

} else {

$MB.n_warning(r.msg);

}

});

}

function exportIpCsv(){

$.post(ctx+”vlan/csv”,$(“.vlan-table-form”).serialize(),function(r){

if (r.code === 0) {

window.location.href = “common/download?fileName=” + r.msg + “&delete=” + true;

} else {

$MB.n_warning(r.msg);

}

});

}

五、配置权限

菜单管理配置如下

角色权限配置如下,标记的部分全部打勾。

六、运行结果