在使用JPA(Java Persistence API)和Thymeleaf进行增删改查(CRUD)操作时,你通常会结合Spring Boot框架来简化开发过程。以下是一个基本的步骤指南和示例代码,展示如何使用这些技术来实现CRUD操作。
1. 搭建Spring Boot项目
首先,你需要创建一个Spring Boot项目,并添加必要的依赖项,如Spring Web, Spring Data JPA, Thymeleaf, 以及数据库驱动(如H2, MySQL等)。
2. 配置数据库
在application.properties
或application.yml
中配置数据库连接和其他JPA相关设置。
spring:
# 程序名称
# application:
# name:
#配置数据源
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource #使用阿里巴巴Druid数据源
dynamic:
primary: master # 这里指定了主数据源的名称
datasource:
master:
url: jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource #使用阿里巴巴Druid数据源
#??mybatis????
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.bdqn.iotdevices.pojo
#??????
logging:
level:
com:
bdqn:
iotdevices:
mapper: debug
com.baomidou: debug #??MyBatis-Plus?????debug
org.springframework.jdbc.datasource.init: debug #??DataSource????????debug
#????
server:
port: 8080
servlet:
encoding:
charset: UTF-8
3. 创建实体类
定义一个实体类,映射到数据库表。
package com.bdqn.iotdevices.pojo;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "iot_devices")
public class IotDevice implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "device_id")
private Long deviceId;
@Column(name = "device_name")
private String deviceName;
private String manufacturer;
private String model;
/**
* 安装日期
*/
@Column(name = "installation_date")
private Date installationDate;
/**
* 最后维护日期
*/
@Column(name = "last_Maintenance_date")
private Date lastMaintenanceDate;
private String location;
private String ip;
private Long status;
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Date getInstallationDate() {
return installationDate;
}
public void setInstallationDate(Date installationDate) {
this.installationDate = installationDate;
}
public Date getLastMaintenanceDate() {
return lastMaintenanceDate;
}
public void setLastMaintenanceDate(Date lastMaintenanceDate) {
this.lastMaintenanceDate = lastMaintenanceDate;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Long getStatus() {
return status;
}
public void setStatus(Long status) {
this.status = status;
}
}
4. 创建JPA仓库
创建一个继承自JpaRepository
的接口,用于数据库操作。
import org.springframework.data.jpa.repository.JpaRepository;
public interface IotDeviceRepository extends JpaRepository<User, Long> { }
5. 创建服务层
(可选)创建一个服务层来处理业务逻辑。
package com.bdqn.iotdevices.service;
import com.bdqn.iotdevices.pojo.IotDevice;
import java.util.List;
/**
* @author YangQingFeng
* @version 2024-09-18
*/
public interface IotDeviceService {
/**
* 查询所有设备
* @return
*/
List<IotDevice> list();
/**
* 根据主键删除
* @param id
* @return
*/
int delete(Long id);
/**
* 插入数据
* @param record
* @return
*/
int insert(IotDevice record);
/**
* 根据Id查询数据
* @param id
* @return
*/
IotDevice selectById(Long id);
/**
* 修改
* @param record
* @return
*/
int update(IotDevice record);
}
6. 创建控制器
创建控制器来处理HTTP请求。
package com.bdqn.iotdevices.controller;
import com.bdqn.iotdevices.pojo.IotDevice;
import com.bdqn.iotdevices.service.IotDeviceService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
/**
* @version 2024-09-23
* @Author:T369曹任柱
*/
@Controller
public class IotDeviceController {
@Resource
IotDeviceService iotDeviceService;
@GetMapping("/list")
public String list(Model model){
List<IotDevice> iotDevice = iotDeviceService.list();
model.addAttribute("iotDevice", iotDevice);
return "/list";
}
@GetMapping("/update")
public String update(Long id,Model model){
IotDevice iotDevice = iotDeviceService.selectById(id);
model.addAttribute("iotDevices",iotDevice);
return "update";
}
@PostMapping("/doUpdate")
public String doUpdate(Model model, IotDevice iotDevice){
System.out.println(iotDevice);
int count = iotDeviceService.update(iotDevice);
if(count==0){
model.addAttribute("msg","更新失败");
return "update";
}
return "redirect:/list";
}
@GetMapping("/delete")
public String delete(Long id,Model model){
int count = iotDeviceService.delete(id);
if(count==0){
model.addAttribute("msg","删除失败");
return "/list";
}
return "redirect:/list";
}
}
7. 创建Thymeleaf模板
在src/main/resources/templates
目录下创建Thymeleaf模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 align="center">物联设备信息管理</h1>
<p th:text="${msg}" align="center"></p>
<table border="1" cellspacing="0" cellpadding="0" align="center">
<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="device : ${iotDevice}">
<td th:text="${device.getDeviceId()}"></td>
<td th:text="${device.getDeviceName()}"></td>
<td th:text="${device.manufacturer}"></td>
<td th:text="${device.model}"></td>
<td th:text="${#dates.format(device.getInstallationDate(), 'yyyy-MM-dd')}"></td>
<td th:text="${#dates.format(device.getLastMaintenanceDate(), 'yyyy-MM-dd')}"></td>
<td th:text="${device.location}"></td>
<td th:text="${device.ip}"></td>
<td th:switch="${device.status}">
<span th:case="0">离线</span>
<span th:case="1">在线</span>
<span th:case="2">维护中</span>
</td>
<td>
<a th:href="@{/update(id=${device.deviceId})}">修改</a>
<a th:href="@{/delete(id=${device.deviceId})}">删除</a>
</td>
</tr>
</table>
</body>
</html>
8. 运行和测试
运行Spring Boot应用,并使用浏览器访问定义的URL来测试CRUD操作。