学习进度条
今日所花时间:一小时
今日代码量:100行
博客量:1篇
了解到的知识点: 数据的分页查询,借助写好的PageBean工具类
PageBean
package com.example.littlebabydemo0425.pojo;
import lombok.Data;
import java.util.List;
//分页返回结果对象
@Data
public class PageBean<T>{
private Long total;//总条数
private List<T> items;//当前页数据集合
public PageBean() {
}
public PageBean(Long total, List<T> items) {
this.total = total;
this.items = items;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}
示例:设备列表查询
实体类:Device
package com.example.littlebabydemo0425.pojo;
import jakarta.persistence.*;
import java.util.Date;
@Entity
@Table(name = "device", uniqueConstraints = {
@UniqueConstraint(columnNames = "device_code", name = "idx_device_code")
})
public class Device {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "device_code", length = 64, nullable = false)
private String deviceCode;
@Column(name = "device_name", length = 128, nullable = false)
private String deviceName;
@Column(name = "device_type", length = 32, nullable = false)
private String deviceType;
@Column(name = "location", length = 256)
private String location;
@Column(name = "status", columnDefinition = "tinyint default 1")
private Integer status;
@Column(name = "create_time", columnDefinition = "datetime default CURRENT_TIMESTAMP")
private Date createTime;
@Column(name = "update_time", columnDefinition = "datetime default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP")
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDeviceCode() {
return deviceCode;
}
public void setDeviceCode(String deviceCode) {
this.deviceCode = deviceCode;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
DeviceController
package com.example.littlebabydemo0425.controller;
import com.example.littlebabydemo0425.mapper.DeviceMapper;
import com.example.littlebabydemo0425.pojo.Device;
import com.example.littlebabydemo0425.pojo.PageBean;
import com.example.littlebabydemo0425.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/devices/")
@CrossOrigin(origins = "http://localhost:5173") // 添加CORS支持
public class DevicesController {
@Autowired
private DeviceMapper deviceMapper;
@GetMapping
public Result<PageBean<Device>> list(Integer pageNum,
Integer pageSize,
@RequestParam(required = false)String deviceCode,
@RequestParam(required = false)String deviceType,
@RequestParam(required = false)String deviceName,
@RequestParam(required = false) String status){
PageBean<Device> pb = deviceMapper.list(pageNum,pageSize,deviceCode,deviceType,deviceName,status);
return Result.success(pb);
}
@DeleteMapping("/{deviceCode}")
public Result<String> deleteDevice(@PathVariable String deviceCode) {
deviceMapper.deleteById(deviceCode);
return Result.success(deviceCode);
}
@PostMapping
public ResponseEntity<Result<Device>> createDevice(@RequestBody Device device) {
try {
// 检查设备编号是否已存在
Device existingDevice = deviceMapper.selectByDeviceCode(device.getDeviceCode());
if (existingDevice != null) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Result.error("设备编号已存在"));
}
System.out.println("收到请求,设备数据: " + device); // 调试日志
if(device.getDeviceCode() == null) {
return ResponseEntity.badRequest()
.body(Result.error("设备编号不能为空"));
}
// 设置默认状态为1(正常)
if (device.getStatus() == null) {
device.setStatus(1);
}
// 插入新设备
int result = deviceMapper.insert(device);
if (result > 0) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(Result.success(device));
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Result.error("添加设备失败"));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Result.error("服务器内部错误: " + e.getMessage()));
}
}
}
DeviceMapper
package com.example.littlebabydemo0425.mapper;
import com.example.littlebabydemo0425.pojo.Device;
import com.example.littlebabydemo0425.pojo.PageBean;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import java.util.List;
@Mapper
public interface DeviceMapper {
@Insert("INSERT INTO device (device_code, device_name, device_type, location, status) " +
"VALUES(#{deviceCode}, #{deviceName}, #{deviceType}, #{location}, #{status})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(Device device);
@Update("UPDATE device SET device_name=#{deviceName}, device_type=#{deviceType}, " +
"location=#{location}, status=#{status} WHERE id=#{id}")
int update(Device device);
@Delete("DELETE FROM device WHERE device_code=#{deviceCode}")
int deleteById(String deviceCode);
@Select("SELECT * FROM device WHERE id=#{id}")
Device selectById(Long id);
@Select("SELECT * FROM device WHERE device_code=#{deviceCode}")
Device selectByDeviceCode(String deviceCode);
@Select("SELECT * FROM device")
List<Device> selectAll();
/**
* 分页查询设备列表
* @param pageNum 页码
* @param pageSize 每页大小
* @param deviceCode 设备编码(可选)
* @param deviceName 设备名称(可选)
* @param deviceType 设备类型(可选)
* @param status 设备状态(可选)
* @return 分页结果
*/
default PageBean<Device> list(Integer pageNum, Integer pageSize, String deviceCode, String deviceType,String deviceName, String status) {
PageBean<Device> pb = new PageBean<>();
// 计算偏移量
int offset = (pageNum - 1) * pageSize;
// 查询数据
List<Device> devices = selectByCondition(deviceCode, deviceType,deviceName, status, offset, pageSize);
pb.setItems(devices);
// 查询总数
long total = countByCondition(deviceCode, deviceType, deviceName, status);
pb.setTotal(total);
return pb;
}
@SelectProvider(type = DeviceSqlProvider.class, method = "selectByCondition")
List<Device> selectByCondition(
@Param("deviceCode") String deviceCode,
@Param("deviceType") String deviceType,
@Param("deviceName") String deviceName,
@Param("status") String status,
@Param("offset") int offset,
@Param("pageSize") int pageSize);
@SelectProvider(type = DeviceSqlProvider.class, method = "countByCondition")
long countByCondition(
@Param("deviceCode") String deviceCode,
@Param("deviceType") String deviceType,
@Param("deviceName") String deviceName,
@Param("status") String status);
// SQL提供类
class DeviceSqlProvider {
public String selectByCondition(
@Param("deviceCode") String deviceCode,
@Param("deviceType") String deviceType,
@Param("deviceName") String deviceName,
@Param("status") String status,
@Param("offset") int offset,
@Param("pageSize") int pageSize) {
return new SQL() {{
SELECT("*");
FROM("device");
if (deviceCode != null && !deviceCode.isEmpty()) {
WHERE("device_code LIKE CONCAT('%', #{deviceCode}, '%')");
}
if (deviceType != null && !deviceType.isEmpty()) {
// 修改为根据设备类型进行模糊匹配
WHERE("device_type LIKE CONCAT('%', #{deviceType}, '%')");
}
if (deviceName != null && !deviceName.isEmpty()) {
WHERE("device_name LIKE CONCAT('%', #{deviceName}, '%')");
}
if (status != null && !status.isEmpty()) {
WHERE("status = #{status}");
}
ORDER_BY("id DESC");
}}.toString() + " LIMIT #{offset}, #{pageSize}";
}
public String countByCondition(
@Param("deviceCode") String deviceCode,
@Param("deviceType") String deviceType,
@Param("deviceName") String deviceName,
@Param("status") String status) {
return new SQL() {{
SELECT("COUNT(*)");
FROM("device");
if (deviceCode != null && !deviceCode.isEmpty()) {
WHERE("device_code LIKE CONCAT('%', #{deviceCode}, '%')");
}
if (deviceType != null && !deviceType.isEmpty()) {
// 修改为根据设备类型进行模糊匹配
WHERE("device_type LIKE CONCAT('%', #{deviceType}, '%')");
}
if (deviceName != null && !deviceName.isEmpty()) {
WHERE("device_name LIKE CONCAT('%', #{deviceName}, '%')");
}
if (status != null && !status.isEmpty()) {
WHERE("status = #{status}");
}
}}.toString();
}
}
}
根据以上代码,能够完成设备列表的信息分页查询和显示,当然还能够根据设备类型,设备名称,设备编号,设备状态进行条件查询

浙公网安备 33010602011771号