综合实践:JPA+Thymeleaf增删改查

为了演示如何使用JPA(Java Persistence API)结合Thymeleaf来创建一个简单的增删改查(CRUD)应用,我们需要创建一个Spring Boot项目。下面,我将引导你完成创建这样一个应用的基本步骤。

1. 创建Spring Boot项目

首先,你需要创建一个Spring Boot项目。

2. 配置数据库

src/main/resources/application.properties文件中配置你的数据库连接。以下是一个使用H2内存数据库的示例配置:

application.properties复制代码
spring.application.name=iot-manager

spring.thymeleaf.cache=false

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

logging.level.root=warn
logging.level.com.bdqn.iotmanager.mapper=trace
logging.pattern.console=%p%m%n
#加载sql日志
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.bdqn.entity
#MVC配置
#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化大小、最小、最大连接数
spring.datasource.druid.initial-size=3
spring.datasource.druid.min-idle=3
spring.datasource.druid.max-active=10
#配置获取连接等待超时的时间
spring.datasource.druid.max-wait=60000
#监控后台账号和密码
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#配置StatFilter
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000

3. 创建实体类

例如,我们创建一个简单的IotDevices实体类:

package com.bdqn.entity;

import lombok.Data;
import lombok.ToString;

import java.io.Serial;
import java.io.Serializable;

@Data
@ToString
public class IotDevices implements Serializable {
  @Serial
  private static final long serialVersionUID = 1L;

  private Long deviceId;
  private String deviceName;
  private String manufacturer;
  private String model;
  private String installationDate;
  private String lastMaintenanceDate;
  private String location;
  private String ip;
  private Integer status;

}

4. 编写Mapper SQL

<?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">
<!-- namespace是实体类接口文件路径 -->
<mapper namespace="com.bdqn.mapper.IotDevicesMapper">

    <resultMap id="IotDevicesInfo" type="com.bdqn.entity.IotDevices">
        <id property="deviceId" column="device_id"/>
        <result property="deviceName" column="device_name"/>
        <result property="installationDate" column="installation_date"/>
        <result property="lastMaintenanceDate" column="last_maintenance_date"/>
    </resultMap>

    <select id="getList" resultMap="IotDevicesInfo">
        select * from iot_devices order by installation_date desc
    </select>
    <select id="iotDevicesById" resultMap="IotDevicesInfo">
        select * from iot_devices where device_id = #{deviceId}
    </select>
    <update id="upd">
        update iot_devices
        <set>
            <if test="deviceName != null and deviceName != ''">
                ,device_name = #{deviceName}
            </if>
            <if test="manufacturer != null and manufacturer != ''">
                ,manufacturer = #{manufacturer}
            </if>
            <if test="model != null and model != ''">
                ,model = #{model}
            </if>
            <if test="installationDate != null and installationDate != ''">
                ,installation_date = #{installationDate}
            </if>
            <if test="lastMaintenanceDate != null and lastMaintenanceDate != ''">
                ,last_maintenance_date = #{lastMaintenanceDate}
            </if>
            <if test="location != null and location != ''">
                ,location = #{location}
            </if>
            <if test="ip != null and ip != ''">
                ,ip = #{ip}
            </if>
            <if test="status != null">
                ,status = #{status}
            </if>
        </set>
        where
        device_id = #{deviceId}
    </update>
    <delete id="del">
        delete from iot_devices where device_id = #{deviceId}
    </delete>
</mapper><?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">
<!-- namespace是实体类接口文件路径 -->
<mapper namespace="com.bdqn.mapper.IotDevicesMapper">

    <resultMap id="IotDevicesInfo" type="com.bdqn.entity.IotDevices">
        <id property="deviceId" column="device_id"/>
        <result property="deviceName" column="device_name"/>
        <result property="installationDate" column="installation_date"/>
        <result property="lastMaintenanceDate" column="last_maintenance_date"/>
    </resultMap>

    <select id="getList" resultMap="IotDevicesInfo">
        select * from iot_devices order by installation_date desc
    </select>
    <select id="iotDevicesById" resultMap="IotDevicesInfo">
        select * from iot_devices where device_id = #{deviceId}
    </select>
    <update id="upd">
        update iot_devices
        <set>
            <if test="deviceName != null and deviceName != ''">
                ,device_name = #{deviceName}
            </if>
            <if test="manufacturer != null and manufacturer != ''">
                ,manufacturer = #{manufacturer}
            </if>
            <if test="model != null and model != ''">
                ,model = #{model}
            </if>
            <if test="installationDate != null and installationDate != ''">
                ,installation_date = #{installationDate}
            </if>
            <if test="lastMaintenanceDate != null and lastMaintenanceDate != ''">
                ,last_maintenance_date = #{lastMaintenanceDate}
            </if>
            <if test="location != null and location != ''">
                ,location = #{location}
            </if>
            <if test="ip != null and ip != ''">
                ,ip = #{ip}
            </if>
            <if test="status != null">
                ,status = #{status}
            </if>
        </set>
        where
        device_id = #{deviceId}
    </update>
    <delete id="del">
        delete from iot_devices where device_id = #{deviceId}
    </delete>
</mapper>

5. 创建服务层

创建一个服务层来处理业务逻辑:

package com.bdqn.service;

import com.bdqn.entity.IotDevices;

import java.util.List;

public interface IotDevicesService {
    List<IotDevices> getList();
    IotDevices iotDevicesById(Long id);
    int upd(IotDevices iotDevices);
    int del(Long id);
}

6. 创建控制器

创建一个控制器来处理HTTP请求并调用服务层:

package com.bdqn.controller;

import com.bdqn.entity.IotDevices;
import com.bdqn.service.IotDevicesService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class IotDevicesController {

    @Resource
    private IotDevicesService iotDevicesService;

    @GetMapping("/list")
    public String getList(Model model) {
        List<IotDevices> list = iotDevicesService.getList();
        model.addAttribute("list", list);
        for (IotDevices iotDevices : list) {
            System.out.println(iotDevices);
        }
        return "list";
    }

    // 使用@ResponseBody注解,将方法的返回值直接作为响应体返回
    @ResponseBody
    // 使用@GetMapping注解,指定请求路径为"/del/{id}"
    @GetMapping("/del/{id}")
    // 定义一个方法,参数为id,类型为Long
    public String del(@PathVariable Long id) {
        // 调用iotDevicesService的del方法,传入id,返回值为num
        int num = iotDevicesService.del(id);
        // 定义一个字符串变量result,初始值为"fales"
        String result = "fales";
        // 如果num大于0,则将result的值改为"ture"
        if (num > 0) {
            result = "true";
        }
        // 返回result
        return result;
    }

    @GetMapping("/toUpd/{id}")
    public String upd(@PathVariable Long id, Model model){
        IotDevices iotDevices = iotDevicesService.iotDevicesById(id);
        System.out.println(iotDevices);
        model.addAttribute("iotDevices",iotDevices);
        return "update";
    }

    @PostMapping("/doUpd")
    public String doUpd(IotDevices iotDevices, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int row = iotDevicesService.upd(iotDevices);
        if (row > 0){
            out.print("<script>alert('修改成功!');location.href = '/list';</script>");
        }else{
            out.print("<script>alert('修改失败!');location.href = '/toUpd/" + iotDevices.getDeviceId() + "';</script>");
        }
        out.flush();
        out.close();
        return null;
    }

}

7. 创建Thymeleaf模板

src/main/resources/templates/list.html目录下创建HTML模板。例如,list.html用于显示所有Person对象:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        td{
            text-align: center;
        }
        table {
            border-collapse: collapse;

        }
        th{
            background-color: dimgray;
        }
        table td,th {
            border:1px solid black;

        }
        a{
            text-decoration: none;
        }
    </style>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<table>
    <h1>物联设备信息管理</h1>
    <tr>
        <th>设备ID</th>
        <th>设备名称</th>
        <th>设备制造商</th>
        <th>型号</th>
        <th>安装日期</th>
        <th>最后维护日期</th>
        <th>设备位置</th>
        <th>设备IP地址</th>
        <th>设备状态</th>
        <th>操作</th>
    </tr>
    <tr th:each="iotDevices,status : ${list}">
        <td th:text="${iotDevices.deviceId}">设备ID</td>
        <td th:text="${iotDevices.deviceName}">设备名称</td>
        <td th:text="${iotDevices.manufacturer}">设备制造商</td>
        <td th:text="${iotDevices.model}">型号</td>
        <td th:text="${iotDevices.installationDate}">安装日期</td>
        <td th:text="${iotDevices.lastMaintenanceDate}">最后维护日期</td>
        <td th:text="${iotDevices.location}">设备位置</td>
        <td th:text="${iotDevices.ip}">设备IP地址</td>
        <td th:switch="${iotDevices.status}">
            <span th:case="0" style="color: dimgray;font-weight: bold">离线</span>
            <span th:case="1" style="color: #0ac70a;font-weight: bold">在线</span>
            <span th:case="2" style="color: red;font-weight: bold">维护中</span>
        </td>
        <td>
            <a th:href="'/toUpd/' + ${iotDevices.deviceId}" >修改</a>&nbsp;&nbsp;
            <a href="#" th:onclick="'del(' + ${iotDevices.deviceId} + ')'">删除</a>
        </td>
    </tr>

</table>
<script>
    $("tr:odd").css("background-color","#fcd1bd");
    function del(id){
        if (!confirm("确定要删除此条数据吗?")){
            return;
        }
        $.ajax({
            url:"/del/" + id,
            type:"GET",
            dataType:"text",
            success:function (res){
                if (res == "true"){
                    alert("删除成功!");
                }else{
                    alert("删除失败!");
                }
                location.href = "/list";
            }
        })
    }
</script>
</body>
</html>

8. 运行应用

现在,你可以运行你的Spring Boot应用,并通过浏览器访问http://localhost:8080/list来查看你的CRUD界面(虽然这里只显示了列表页面)。你需要进一步实现表单和路由来完整实现增删改功能。

总结

这个简单的例子展示了如何使用Spring Boot、JPA和Thymeleaf来创建一个具有基本CRUD功能的Web应用。当然,这只是一个起点,实际应用中可能需要更复杂的业务逻辑、更复杂的UI以及更多的安全和性能考虑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值