Day87.二手房管理: 数据字典 (zTree组件)、小区管理

目录

 

数据字典

一、搭建service-house模块

二、zTree渲染、简单Json格式

三、页面开发(实现)

1. 引入zTree组件 (静态文件)

2. 新增页面:dict/index.html 

3、主界面添加左侧导航

四、dubbo消费端接口 (DictController层)

五、dubbo服务端接口

1、service-api 新建接口 DictService

2、service-house 新建实现类 DictServiceImpl 

3、DictDao 接口、xml实现

六、断点测试:

小区管理

 一、页面

1. index

2. create

3. edit

二、CommunityController

三、CommunityService

四、CommunityServiceImpl

五、CommunityDao

六、CommunityDao.xml


数据字典

数据字典是数的结构,需要用到组件:zTree

一、搭建service-house模块

搭建方式与service-acl一致,这里可直接复制service-acl模块,改名为service-house模块

1,在service模块中,复制service-acl模块,改名为service-house模块 (建议在硬盘中操作)

2,修改pom.xml文件,只是修改名称和 Jetty端口

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>service</artifactId>
        <groupId>com.atguigu</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>service-house</artifactId>
    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.15.v20190215</version>
                <configuration>
                    <!-- 如果检测到项目有更改则自动热部署,每隔n秒扫描一次。默认为0,即不扫描-->
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <webAppConfig>
                        <!--指定web项目的根路径,默认为/ -->
                        <contextPath>/</contextPath>
                    </webAppConfig>
                    <httpConnector>
                        <!--端口号,默认 8080-->
                        <port>7002</port>
                    </httpConnector>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

4,父模块service 聚合service-house,识别项目

    <modules>
        <module>service-acl</module>
        <module>service-house</module>
    </modules>

5,修改 spring-registry.xml 文件,发布的应用名称与服务端端口

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://code.alibabatech.com/schema/dubbo
                            http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    <!-- 指定应用名称 -->
    <dubbo:application name="service-house"/>
    <!--指定暴露服务的端口,如果不指定默认为20880 -->
    <dubbo:protocol name="dubbo" port="20882"/>
    <!--指定服务注册中心地址-->
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <!--批量扫描,发布服务-->
    <dubbo:annotation package="com.atguigu"/>
</beans>

6,删除mapper下的xml,与各种实现类

二、zTree渲染、简单Json格式

数据字典我们使用zTree渲染

在线文档:Demo [zTree -- jQuery tree plug-ins.]

异步加载 数据节点:先展示父节点,当点击父节点时,再去加载子节点。而不是同一时刻全部加载。

实现方式:

1、构建服务器端接口:根据上级节点id获取子节点数据列表,返回特定数据格式:

2、参照示例,进行页面渲染;

数据库中的数据,需要封装成什么样的格式才能通过zTree展示?

1、标准 JSON 数据

2、简单 JSON 数据

zTree 会根据返回的 id 与 pId进行关联,形成父子关系

在角色管理-分配权限功能中,也需要展示树结构

三、页面开发(实现)

1. 引入zTree组件 (静态文件)

将资源文件中的zTree_v3文件夹复制到static/js/plugins目录下

2. 新增页面:dict/index.html 

zTree依赖jquery,需要先将jquery引用,但head文件已引用

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!--插入代码片段(已包含JQuery)-->
<head th:include="common/head :: head"></head>
<!--引入zTree组件-->
<link rel="stylesheet" th:href="@{/static/js/plugins/zTree_v3/zTreeStyle.css}" type="text/css">
<script type="text/javascript" th:src="@{/static/js/plugins/zTree_v3/jquery.ztree.core.js}"></script>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="ibox float-e-margins">
        <div class="ibox-content" style="width: 98%;">

            <!--展示数据的标签 通过#treeDemo cs选择器指定-->
            <div class="zTreeDemoBackground left">
                <ul id="treeDemo" class="ztree"></ul>
            </div>

        </div>
    </div>
</div>

<script th:inline="javascript">
    $(function(){
        // 文档地址:http://www.treejs.cn/v3/demo.php#_108
        var setting = {
            async: {    //异步的
                enable: true,   //启用异步方式加载树结构
                url:"/dict/findZnodes", //指定请求地址,获取数节点数据
                type:"get",     //请求方式
                //id为数节点的主键,作为参数发送
                autoParam:["id"],   //传递树节点的属性值给服务器,属性名称固定
                //otherParam:{"otherParam":"zTreeAsyncTest"},  其他参数,属性名自定义
                dataFilter: filter  //数据过滤
            }
        };
        //对返回的数据进行过滤  result 表示controller方法返回的结果,将数据封装到result对象中
        function filter(treeId, parentNode, result) {
            var childNodes = result.data
            if (!childNodes) return null;   //如果为空,取空
            for (var i=0, l=childNodes.length; i<l; i++) {
                //将多个.n替换为. 赋值给name
                childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            }
            return childNodes;
        }
        //zTree初始化,将数据渲染到1d=treeDemo标签内
        $(document).ready(function(){
            //在treeDemo标签中初始化zTree,通过setting发起请求
            $.fn.zTree.init($("#treeDemo"), setting);
        });
    });
</script>
</body>
</html>

3、主界面添加左侧导航

<a class="J_menuItem" href="/dict" data-index="0">数据字典</a>

四、dubbo消费端接口 (DictController层)

先写完一套组件,再进行功能实现!! (Controller->Service->ServiceImpl->Dao->xml)

web-admin下,新建DictController

//二手房管理
@Controller
@RequestMapping("/dict")
public class DictController extends BaseController {

    private static final String PAGE_INDEX = "dict/index";
    //注意,Dubbo下的Reference注解
    @Reference
    DictService dictService;

    //数据字典
    @RequestMapping("/findZnodes")
    @ResponseBody   //响应体 异步返回数据
    //通过节点id获取子节点集合,并返回; defaultValue="0": 第一次访问时还没有树,因此赋值为0,查询根节点的子节点
    public Result findZnodes(@RequestParam(value = "id",required = false,defaultValue = "0") Long parentId){

        //传递的是节点的id,作为外键 (parentId) 来使用; 每一个树节点都是一个json对象,用map集合来表示json
        //[{ id:1, pId:0, name:"全部分类", isParent:true}]
        List<Map<String,Object>> data = dictService.findZnodesByParentId(parentId);

        //工具类 将数据封装到Result对象上,返回json串
        return Result.ok(data);
    }

    @RequestMapping
    public String index(){
        return PAGE_INDEX;
    }
}

五、dubbo服务端接口

1、service-api 新建接口 DictService

public interface DictService extends BaseService<Dict> {
    List<Map<String, Object>> findZnodesByParentId(Long parentId);

    List<Dict> findListByParentId(Long parentId);
}

2、service-house 新建实现类 DictServiceImpl 

//发布服务,注意导包,指定发布的接口类
@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Autowired
    DictDao dictDao;

    @Override
    public BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

    @Override
    public List<Map<String, Object>> findZnodesByParentId(Long parentId) {
        //返回的是list,需要转换为map。虽然可以返回map类型的集合,但是需要做业务处理,所以还是返回为实体对象
        List<Dict> list = dictDao.findZnodesByParentId(parentId);

        //需要进行类型转换
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        for (Dict dict : list) {
            //代表一个节点: [{ id:1, pId:0, name:"全部分类", isParent:true}]
            Map<String, Object> map = new HashMap<>();
            map.put("id",dict.getId());
            map.put("pId",dict.getParentId());
            map.put("name",dict.getName());

            //isParent 表示当前节点是否为父节点;有孩子就是父节点 (样式需要)
            Long id = dict.getId();
            Long pId = id;
            //调用Dao层方法判断是否有子节点 (是否为父节点)
            int count = dictDao.countIsParent(pId); //根据pid统计孩子数量
            map.put("isParent", count > 0 ? true : false);
            
            data.add(map);
        }

        return data;
    }
}

3、DictDao 接口、xml实现

(xml文件复制,修改即可)

package com.atguigu.dao;

import com.atguigu.base.BaseDao;
import com.atguigu.entity.Dict;
import java.util.List;

public interface DictDao extends BaseDao<Dict> {
    List<Dict> findListByParentId(Long parentId);
    Integer countIsParent(Long id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.atguigu.dao.DictDao">

    <!--映射: (ORM) Object Relationship Mapping-->
    <resultMap id="Dict" type="Dict">
        <id property="id" column="id"></id>
        <result column="parent_id" property="parentId" ></result>
        <result column="name" property="name" ></result>
        <result column="dict_code" property="dictCode" ></result>
        <result column="create_time" property="createTime" ></result>
        <result column="update_time" property="updateTime" ></result>
        <result column="is_deleted" property="isDeleted" ></result>
    </resultMap>
    <!--复用查询的字段-->
    <sql id="column">
           id,parent_id,name,dict_code,create_time,update_time,is_deleted
    </sql>

    <!--查询去全部子节点-->
    <select id="findZnodesByParentId" parameterType="long" resultMap="Dict">
        select <include refid="column"></include>
        from hse_dict
        where parent_id=#{parentId}
    </select>
    <!--统计是否有子节点(判断是否为父节点)-->
    <select id="countIsParent" parameterType="long" resultType="int">
        select count(*)
        from hse_dict
        where parent_id=#{parentId}
    </select>
    

    <!--增删改查实际没有用到,删除了分页查询-->
    <!--添加 主键回填-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into hse_dict(parent_id,name,dict_code)
        values (#{parentId},#{name},#{dictCode})
    </insert>
    <!--根据id查询-->
    <select id="selectById" resultType="Dict">
        select <include refid="column"></include>
        from hse_dict
        where id = #{id} and is_deleted = 0;
    </select>
    <!--修改-->
    <update id="update">
        update hse_dict
        <set>
            <if test="parentId!=null and parentId!=''">
                parent_id = #{parentId},
            </if>
            <if test="name!=null and name!=''">
                name = #{name},
            </if>
            <if test="dictCode!=null and dictCode!=''">
                dictCode = #{dictCode},
            </if>
            update_time = now()
        </set>
        where id = #{id}
    </update>
    <!--软删除:就是修改表的is_deleted字段值: 0 表示正常    1 表示被删除-->
    <delete id="delete">
        update hse_dict set is_deleted = 1 ,update_time = now() where id = #{id}
    </delete>
</mapper>

六、断点测试:

第一次访问时:

 

点击全部分类时:
 

小区管理

小区管理重点:二级联动:区域与板块、列表回显

区域与板块数据在数据字典里面,通过编码:beijing,可以获取区域数据

添加小区保存的是区域与板块的数据字典id,因此还需要根据字典id获取字段名称

因此数据字典需提供3个接口:

1、通过编码获取子节点数据(区域数据)

2、通过节点id获取子节点数据(通过区域id,获取板块数据)

3、通过字典id获取字典名称

 一、页面

1. index

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head th:include="common/head :: head"></head>

<body class="gray-bg">
<form id="ec" th:action="@{/community}" method="post">
    <div class="wrapper wrapper-content animated fadeInRight">

        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-content">
                        <table class="table form-table margin-bottom10">
                            <tr>
                                <td>
                                    <input type="text" name="name" th:value="${#maps.containsKey(filters, 'name')} ? ${filters.name} : ''" placeholder="小区名称" class="input-sm form-control"/>
                                </td>
                                <td>
                                    <select name="areaId" id="areaId" class="form-control">
                                        <option value="">-请选择区域-</option>
                                        <option th:each="item,it : ${areaList}" th:text="${item.name}" th:value="${item.id}" th:selected="${item.id} eq ${filters.areaId}">-选择区域-</option>
                                    </select>
                                </td>
                                <td>
                                    <select name="plateId" id="plateId" class="form-control">
                                        <option value="">-请选择-</option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                        <div>
                            <button type="submit" class="btn btn-sm btn-primary"> 搜索</button>
                            <button type="button" class="btn btn-sm btn-primary create"> 新增</button>
                            <button type="button" id="loading-example-btn" onclick="javascript:window.location.reload();" class="btn btn-white btn-sm">刷新</button>
                        </div>
                        <table class="table table-striped table-bordered table-hover dataTables-example">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th>小区名称</th>
                                <th>区域</th>
                                <th>板块</th>
                                <th>详细地址</th>
                                <th>建筑年代</th>
                                <th>创建时间</th>
                                <th>操作 </th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr class="gradeX" th:each="item,it: ${page.list}">
                                <td class="text-center" th:text="${it.count}">11</td>
                                <td th:text="${item.name}">22</td>
                                <td th:text="${item.areaName}">33</td>
                                <td th:text="${item.plateName}">22</td>
                                <td th:text="${item.address}">22</td>
                                <td th:text="${item.buildYears}">22</td>
                                <td th:text="${#dates.format(item.createTime,'yyyy-MM-dd HH:mm:ss')}" >33</td>
                                <td class="text-center">
                                    <a class="edit" th:attr="data-id=${item.id}">修改</a>
                                    <a class="delete" th:attr="data-id=${item.id}">删除</a>
                                </td>
                            </tr>
                            </tbody>
                        </table>

                        <div class="row" th:include="common/pagination :: pagination"></div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<script th:inline="javascript">

    $(function(){    //页面加载时触发
        $(".create").on("click",function () {
            opt.openWin('/community/create','新增',630,430)
        });
        $(".edit").on("click",function () {
            var id = $(this).attr("data-id");
            opt.openWin('/community/edit/' + id,'修改',580,430);
        });
        $(".delete").on("click",function(){
            var id = $(this).attr("data-id");
            opt.confirm('/community/delete/'+id);
        });

        $("#areaId").bind("change",function() { //绑定下拉列表的change事件
            var areaId = $("#areaId").val();    //获取下拉列的value属性值
            if(areaId == '') return     //如果选中的下拉列表的默认选项,areaId==''
            $("#plateId").empty();      //将select下拉的option标签清空

            //局部刷新板块下拉列选
            $.get("/dict/findListByParentId/" + areaId,function(response) {      //异步请求获取区域对应版本集合
                $("<option value=''>-请选择板块-</option>").appendTo("#plateId"); //往select下拉列表选中默认选项
                var res = JSON.parse(response)               //解析controller返回的json串(Result序列化生成),转为json对象
                $.each(res.data, function(i,item) {          //获取板块集合:res.data 进行迭代,每次迭代回调此函数,参数:索引,集合元素(dict)
                    var plateId = [[${filters.plateId}]];    //往select下拉列表选中增加默认选项
                    if(item.id == plateId) {
                        $("<option></option>").val(item.id).text(item.name).attr('selected', 'true').appendTo("#plateId");
                    } else {
                        $("<option></option>").val(item.id).text(item.name).appendTo("#plateId");
                    }
                });
            });
        });
        // 触发 select 元素的 change 事件:
        $("#areaId").trigger("change");
    });
</script>
</body>
</html>

2. create

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="common/head :: head"></head>
<script type="text/javascript">
    $(function(){
        $("#areaId").bind("change",function() {
            var areaId = $("#areaId").val();
            $("#plateId").empty();
            $.get("/dict/findListByParentId/" + areaId,function(response) {
                var res = JSON.parse(response)
                $.each(res.data, function(i,item) {
                    $("<option></option>").val(item.id).text(item.name).appendTo("#plateId");
                });
            });
        });
    });
</script>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="ibox float-e-margins">
        <div class="ibox-content" style="width: 98%;">
            <form id="ec" action="/community/save" method="post" class="form-horizontal">
                <div class="form-group">
                    <label class="col-sm-2 control-label">小区名称:</label>
                    <div class="col-sm-10">
                        <input type="text" name="name" id="name" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">描述:</label>
                    <div class="col-sm-10">
                        <input type="text" name="description" id="description" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">区域:</label>
                    <div class="col-sm-10">
                        <select name="areaId" id="areaId" class="form-control">
                            <option value="">-请选择-</option>
                            <option th:each="item,it : ${areaList}" th:text="${item.name}" th:value="${item.id}">-选择区域-</option>
                        </select>
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">板块:</label>
                    <div class="col-sm-10">
                        <select name="plateId" id="plateId" class="form-control">
                            <option value="">-请选择-</option>
                        </select>
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">详细地址:</label>
                    <div class="col-sm-10">
                        <input type="text" name="address" id="address" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">建筑年代:</label>
                    <div class="col-sm-10">
                        <input type="text" name="buildYears" id="buildYears" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">物业价格(元/平):</label>
                    <div class="col-sm-10">
                        <input type="text" name="propertyPrice" id="propertyPrice" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">物业公司:</label>
                    <div class="col-sm-10">
                        <input type="text" name="propertyCompany" id="propertyCompany" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">开发商:</label>
                    <div class="col-sm-10">
                        <input type="text" name="developer" id="developer" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">楼栋数:</label>
                    <div class="col-sm-10">
                        <input type="text" name="buildNum" id="buildNum" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">房屋数:</label>
                    <div class="col-sm-10">
                        <input type="text" name="houseNum" id="houseNum" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">均价(万元/平):</label>
                    <div class="col-sm-10">
                        <input type="text" name="averagePrice" id="averagePrice" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <div class="col-sm-4 col-sm-offset-2 text-right">
                        <button class="btn btn-primary" type="submit">确定</button>
                        <button class="btn btn-white" type="button" onclick="javascript:opt.closeWin();" value="取消">取消</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

3. edit

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="common/head :: head"></head>
<script type="text/javascript">
    $(function(){   //页面加载时触发
        $("#areaId").bind("change",function() {
            var areaId = $("#areaId").val();
            if(areaId == '') return
            $("#plateId").empty();
            $.get("/dict/findListByParentId/" + areaId,function(response) {
                var res = JSON.parse(response)
                $.each(res.data, function(i,item) {
                    var plateId = [[${community.plateId}]];
                    if(item.id == plateId) {
                        $("<option></option>").val(item.id).text(item.name).attr('selected', 'true').appendTo("#plateId");
                    } else {
                        $("<option></option>").val(item.id).text(item.name).appendTo("#plateId");
                    }
                });
            });
        });
        // 触发 select 元素的 change 事件:
        $("#areaId").trigger("change");
    });
</script>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="ibox float-e-margins">
        <div class="ibox-content" style="width: 98%;">
            <form id="ec" th:action="@{/community/update}" method="post" class="form-horizontal">
                <input type="hidden" name="id" th:value="${community.id}">
                <div class="form-group">
                    <label class="col-sm-2 control-label">小区名称:</label>
                    <div class="col-sm-10">
                        <input type="text" name="name" id="name" th:value="${community.name}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">描述:</label>
                    <div class="col-sm-10">
                        <input type="text" name="description" id="description" th:value="${community.description}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">区域:</label>
                    <div class="col-sm-10">
                        <select name="areaId" id="areaId" class="form-control">
                            <option value="">-选择区域-</option>
                            <option th:each="item,it : ${areaList}" th:text="${item.name}" th:value="${item.id}" th:selected="${item.id} eq ${community.areaId}">-选择区域-</option>
                        </select>
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">板块:</label>
                    <div class="col-sm-10">
                        <select name="plateId" id="plateId" class="form-control">
                            <option value="">-选择板块-</option>
                        </select>
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">详细地址:</label>
                    <div class="col-sm-10">
                        <input type="text" name="address" id="address" th:value="${community.address}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">建筑年代:</label>
                    <div class="col-sm-10">
                        <input type="text" name="buildYears" id="buildYears" th:value="${community.buildYears}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">物业价格(元/平):</label>
                    <div class="col-sm-10">
                        <input type="text" name="propertyPrice" id="propertyPrice" th:value="${community.propertyPrice}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">物业公司:</label>
                    <div class="col-sm-10">
                        <input type="text" name="propertyCompany" id="propertyCompany" th:value="${community.propertyCompany}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">开发商:</label>
                    <div class="col-sm-10">
                        <input type="text" name="developer" id="developer" th:value="${community.developer}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">楼栋数:</label>
                    <div class="col-sm-10">
                        <input type="text" name="buildNum" id="buildNum" th:value="${community.buildNum}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">房屋数:</label>
                    <div class="col-sm-10">
                        <input type="text" name="houseNum" id="houseNum" th:value="${community.houseNum}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">均价(万元/平):</label>
                    <div class="col-sm-10">
                        <input type="text" name="averagePrice" id="averagePrice" th:value="${community.averagePrice}" class="form-control" />
                    </div>
                </div>
                <div class="hr-line-dashed"></div>
                <div class="form-group posf">
                    <div class="col-sm-4 col-sm-offset-2 text-right">
                        <button class="btn btn-primary" type="submit">确定</button>
                        <button class="btn btn-white" type="button" onclick="javascript:opt.closeWin();" value="取消">取消</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

二、CommunityController

package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Community;
import com.atguigu.entity.Dict;
import com.atguigu.service.CommunityService;
import com.atguigu.service.DictService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Date 2022/6/21 9:35
 * @Author by:Plisetsky
 */
@Controller
@RequestMapping("/community")
public class CommunityController extends BaseController {

    private final static String PAGE_INDEX = "community/index";
    private static final String PAGE_CREATE = "community/create";
    private static final String PAGE_EDIT = "community/edit";
    private static final String ACTION_LIST = "redirect:/community";

    @Reference
    CommunityService communityService;

    @Reference
    DictService dictService;


    //删除
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
        communityService.delete(id);
        return ACTION_LIST;
    }
    

    //修改
    @RequestMapping("/update")
    public String update(Community community,HttpServletRequest request){
        communityService.update(community);
        return this.successPage(null,request);
    }

    //前往编辑页面
    @RequestMapping("/edit/{id}")
    public String edit(Map map, @PathVariable("id") Long id){
        List<Dict> areaList = dictService.findListByDictCode("beijing");
        Community community = communityService.getById(id);
        map.put("areaList",areaList);
        map.put("community",community);
        return PAGE_EDIT;
    }

    //添加
    @RequestMapping("/save")
    public String save(Community community,HttpServletRequest request){
        communityService.insert(community);
        //成功页面不传消息默认为 操作成功
        return this.successPage(null,request);
    }

    //前往新增页面
    @RequestMapping("/create")
    public String create(Map map){
        List<Dict> areaList = dictService.findListByDictCode("beijing");
        //数据回显,返回请求参数
        map.put("areaList",areaList);
        return PAGE_CREATE;
    }

    //前往主页
    @RequestMapping
    public String index(HttpServletRequest request,Map map){
        //1. 分页数据查询
        Map<String, Object> filters = getFilters(request);//获取请求参数
        //如果参数为空,返回空字符串"",前台判断显示"请显示区域"
        if(!filters.containsKey("areaId")) {
            filters.put("areaId", "");
        }
        if(!filters.containsKey("plateId")) {
            filters.put("plateId", "");
        }
        //page信息
        PageInfo<Community> page = communityService.findPage(filters);

        //2. 获取下拉列选(区域)
        List<Dict> areaList = dictService.findListByDictCode("beijing");

        //3. 数据回显,返回请求参数
        map.put("areaList",areaList);
        map.put("page",page);
        map.put("filters",filters);

        return PAGE_INDEX;
    }



}

三、CommunityService

package com.atguigu.service;

import com.atguigu.base.BaseService;
import com.atguigu.entity.Community;

import java.util.List;

public interface CommunityService extends BaseService<Community> {


    List<Community> findAll();
}

四、CommunityServiceImpl

接口类省略

package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseService;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.CommunityDao;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Community;
import com.atguigu.service.CommunityService;
import com.atguigu.util.CastUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @Date 2022/6/21 9:36
 * @Author by:Plisetsky
 */
@Service( interfaceClass = CommunityService.class)
@Transactional
public class CommunityServiceImpl extends BaseServiceImpl<Community> implements CommunityService {

    @Autowired
    CommunityDao communityDao;

    @Autowired
    DictDao dictDao;

    @Override
    public BaseDao<Community> getEntityDao() {
        return communityDao;
    }

    //重写分页查询,要显示区域名称而不是id
    @Override
    public PageInfo<Community> findPage(Map<String, Object> filters) {
        //当前页数
        int pageNum = CastUtil.castInt(filters.get("pageNum"), 1);
        //每页显示的记录条数
        int pageSize = CastUtil.castInt(filters.get("pageSize"), 10);

        PageHelper.startPage(pageNum, pageSize);

        Page<Community> page = communityDao.findPage(filters);
        //getNameById,将通过id获取name
        for (Community community : page) {
            community.setAreaName(dictDao.getNameById(community.getAreaId()));
            community.setPlateName(dictDao.getNameById(community.getPlateId()));
        }
        return new PageInfo<Community>(page, 5);
    }

    @Override
    public List<Community> findAll() {
        return communityDao.findAll();
    }

    //重写
    @Override
    public Community getById(Serializable id) {
        Community community = communityDao.selectById(id);
        if(community!=null){
            community.setAreaName(dictDao.getNameById(community.getAreaId()));
            community.setPlateName(dictDao.getNameById(community.getPlateId()));
        }
        return super.getById(id);
    }
}

五、CommunityDao

package com.atguigu.dao;

import com.atguigu.base.BaseDao;
import com.atguigu.entity.Community;

import java.util.List;

/**
*@Date 2022/6/21 9:37
*@Author by:Plisetsky
*/
public interface CommunityDao extends BaseDao<Community> {

    List<Community> findAll();
}

六、CommunityDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.atguigu.dao.CommunityDao">

    <!--映射: (ORM) Object Relationship Mapping-->
    <resultMap id="Community" type="Community">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="description" column="description"/>
        <result property="provinceId" column="province_id"/>
        <result property="cityId" column="city_id"/>
        <result property="areaId" column="area_id"/>
        <result property="plateId" column="plate_id"/>
        <result property="address" column="address"/>
        <result property="longitude" column="longitude"/>
        <result property="latitude" column="latitude"/>
        <result property="buildYears" column="build_years"/>
        <result property="propertyPrice" column="property_price"/>
        <result property="propertyCompany" column="property_company"/>
        <result property="developer" column="developer"/>
        <result property="buildNum" column="build_num"/>
        <result property="houseNum" column="house_num"/>
        <result property="averagePrice" column="average_price"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
        <result property="isDeleted" column="is_deleted"/>
    </resultMap>

    <!--复用查询的字段-->
    <sql id="column">
        id,name,description,province_id,city_id,area_id,plate_id,address,longitude,latitude,build_years,property_price,property_company,developer,build_num,house_num,average_price,create_time,update_time,is_deleted
    </sql>
    <!--添加 主键回填-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into hse_community (
            name ,
            description ,
            province_id ,
            city_id ,
            area_id ,
            plate_id ,
            address ,
            longitude ,
            latitude ,
            build_years ,
            property_price ,
            property_company ,
            developer ,
            build_num ,
            house_num ,
            average_price
        ) values (
            #{name} ,
            #{description} ,
            #{provinceId} ,
            #{cityId} ,
            #{areaId} ,
            #{plateId} ,
            #{address} ,
            #{longitude} ,
            #{latitude} ,
            #{buildYears} ,
            #{propertyPrice} ,
            #{propertyCompany} ,
            #{developer} ,
            #{buildNum} ,
            #{houseNum} ,
            #{averagePrice}
        )
    </insert>

    <!--根据id查询-->
    <select id="selectById" resultType="Community">
        select <include refid="column" />
        from hse_community
        where is_deleted = 0 and id = #{id}
    </select>

    <!--修改-->
    <update id="update" >
        update hse_community set
        <if test="name != null">
            name = #{name} ,
        </if>
        <if test="description != null">
            description = #{description} ,
        </if>
        <if test="provinceId != null">
            province_id = #{provinceId} ,
        </if>
        <if test="cityId != null">
            city_id = #{cityId} ,
        </if>
        <if test="areaId != null">
            area_id = #{areaId} ,
        </if>
        <if test="plateId != null">
            plate_id = #{plateId} ,
        </if>
        <if test="address != null">
            address = #{address} ,
        </if>
        <if test="longitude != null">
            longitude = #{longitude} ,
        </if>
        <if test="latitude != null">
            latitude = #{latitude} ,
        </if>
        <if test="buildYears != null">
            build_years = #{buildYears} ,
        </if>
        <if test="propertyPrice != null">
            property_price = #{propertyPrice} ,
        </if>
        <if test="propertyCompany != null">
            property_company = #{propertyCompany} ,
        </if>
        <if test="developer != null">
            developer = #{developer} ,
        </if>
        <if test="buildNum != null">
            build_num = #{buildNum} ,
        </if>
        <if test="houseNum != null">
            house_num = #{houseNum} ,
        </if>
        <if test="averagePrice != null">
            average_price = #{averagePrice} ,
        </if>
        update_time =  now()
        where
        id = #{id}
    </update>

    <update id="delete">
        update hse_community set
        update_time = now() ,
        is_deleted = 1
        where
        id = #{id}
    </update>

    <sql id="where">
        <where>
            <if test="name != null and name != ''">
                and name like concat('%',#{name},'%')
            </if>
            <if test="areaId != null and areaId != ''">
                and area_id = #{areaId}
            </if>
            <if test="plateId != null and plateId != ''">
                and plate_id = #{plateId}
            </if>
            and is_deleted = 0
        </where>
    </sql>

    <select id="findPage" resultMap="Community">
        select <include refid="column" />
        from hse_community
        <include refid="where"/>
        order by id desc
    </select>

    <select id="findAll" resultMap="Community">
        select id,name
        from hse_community
        where
            is_deleted = 0
        order by id desc
    </select>

</mapper>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值