以下是我的后端编写风格,请按照以下来编写package com.example.staffmanagement.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import com.example.staffmanagement.entity.BomMaterial; import com.example.staffmanagement.service.BomMaterialService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/bom_material") @RequiredArgsConstructor public class BomMaterialController { private final BomMaterialService bomMaterialService; /* 分页 + 关键字 */ @GetMapping public IPage<BomMaterial> page(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size, @RequestParam(required = false) String keyword) { return bomMaterialService.listBomMaterials(keyword, page, size); } /* 单条查询 */ @GetMapping("/{id}") public BomMaterial one(@PathVariable Long id) { return bomMaterialService.getById(id); } /* 新增 */ @PostMapping public Boolean add(@RequestBody BomMaterial bom) { return bomMaterialService.save(bom); } /* 修改 */ @PutMapping("/{id}") public Boolean update(@PathVariable Long id, @RequestBody BomMaterial bom) { bom.setId(id); return bomMaterialService.updateById(bom); } /* 删除 */ @DeleteMapping("/{id}") public Boolean delete(@PathVariable Long id) { return bomMaterialService.removeById(id); } }package com.example.staffmanagement.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.math.BigDecimal; @Data @TableName("smt_bom_material") public class BomMaterial { @TableId(type = IdType.AUTO) private Long id; // 序号 private String bomVersion; // BOM版本 private String materialCode;// 物料编码 private String materialName;// 物料名称 private String spec; // 规格 private BigDecimal qtyPer; // 用量 private BigDecimal orderQty;// 订单总量 private BigDecimal receivedQty; // 到料数量 /* 虚拟字段,对应 generated column,查询时自动填充 */ private BigDecimal shortageQty; // 欠料总数 }package com.example.staffmanagement.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.staffmanagement.entity.BomMaterial; import org.apache.ibatis.annotations.Mapper; @Mapper public interface BomMaterialMapper extends BaseMapper<BomMaterial> { }package com.example.staffmanagement.service.Impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.staffmanagement.entity.BomMaterial; import com.example.staffmanagement.mapper.BomMaterialMapper; import com.example.staffmanagement.service.BomMaterialService; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service public class BomMaterialServiceImpl extends ServiceImpl<BomMaterialMapper, BomMaterial> implements BomMaterialService { @Override public IPage<BomMaterial> listBomMaterials(String keyword, int pageNum, int pageSize) { Page<BomMaterial> page = new Page<>(pageNum, pageSize); LambdaQueryWrapper<BomMaterial> wrapper = new LambdaQueryWrapper<>(); if (StringUtils.hasText(keyword)) { wrapper.like(BomMaterial::getBomVersion, keyword) .or() .like(BomMaterial::getMaterialCode, keyword) .or() .like(BomMaterial::getMaterialName, keyword); } /* 欠料列由数据库 generated column 自动返回,无需手动计算 */ return this.page(page, wrapper); } }package com.example.staffmanagement.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import com.example.staffmanagement.entity.BomMaterial; public interface BomMaterialService extends IService<BomMaterial> { IPage<BomMaterial> listBomMaterials(String keyword, int pageNum, int pageSize); }
时间: 2025-07-19 14:25:30 浏览: 6
<think>我们面临的核心需求是:保存生产计划详情数据,并且要求保存的日期字段在后续不会随着时间变化而改变。这意味着我们需要在保存时就将日期固定下来,存储为不可变的字符串或特定格式的日期值,而不是每次查询时动态生成。
根据之前的设计,我们在前端已经实现了详情弹窗,可以输入每天的计划交付和实际交付数量。现在需要实现后端接口来保存这些数据,并且确保日期字段在保存后不再变化。
解决方案:
1. 后端存储时,将日期字段作为字符串(例如"2024-06-01")存储,而不是使用数据库的日期类型(如DATE)。这样即使时间过去,存储的字符串也不会改变。
2. 在实体类中,使用String类型来表示日期字段。
3. 在保存数据时,前端传递的日期字符串直接存储,不需要做任何转换(因为已经是固定格式的字符串)。
具体步骤:
一、数据库表设计
我们创建一张表来存储生产计划详情(每天的数据)。表结构如下:
```sql
CREATE TABLE production_plan_detail (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
plan_id BIGINT NOT NULL COMMENT '关联的生产计划主表ID',
date_str VARCHAR(10) NOT NULL COMMENT '日期字符串(格式:yyyy-MM-dd)',
planned_quantity INT NOT NULL DEFAULT 0 COMMENT '计划交付数量',
actual_quantity INT NOT NULL DEFAULT 0 COMMENT '实际交付数量',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
UNIQUE KEY uniq_plan_date (plan_id, date_str)
) COMMENT '生产计划详情表';
```
注意:这里使用`date_str`字段存储固定格式的日期字符串(如"2024-06-01"),并且与`plan_id`组成唯一约束,避免同一天重复记录。
二、后端实现(Spring Boot)
1. 创建实体类(使用JPA)
```java
@Entity
@Table(name = "production_plan_detail", uniqueConstraints = {
@UniqueConstraint(columnNames = {"plan_id", "date_str"})
})
public class ProductionPlanDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "plan_id", nullable = false)
private Long planId;
@Column(name = "date_str", nullable = false, length = 10)
private String dateStr;
@Column(name = "planned_quantity", nullable = false)
private Integer plannedQuantity = 0;
@Column(name = "actual_quantity", nullable = false)
private Integer actualQuantity = 0;
@Column(name = "created_at", updatable = false)
@CreationTimestamp
private LocalDateTime createdAt;
@Column(name = "updated_at")
@UpdateTimestamp
private LocalDateTime updatedAt;
// 省略getter和setter
}
```
2. 创建Repository接口
```java
public interface ProductionPlanDetailRepository extends JpaRepository<ProductionPlanDetail, Long> {
// 根据计划ID和日期字符串查找(用于检查是否存在记录)
Optional<ProductionPlanDetail> findByPlanIdAndDateStr(Long planId, String dateStr);
// 根据计划ID查找所有详情
List<ProductionPlanDetail> findByPlanId(Long planId);
// 根据计划ID删除所有详情(可选)
void deleteByPlanId(Long planId);
}
```
3. 创建Service层
```java
@Service
@RequiredArgsConstructor
public class ProductionPlanDetailService {
private final ProductionPlanDetailRepository detailRepository;
// 保存或更新详情数据
@Transactional
public void saveDetails(Long planId, List<ProductionPlanDetailDTO> details) {
// 先删除该计划下原有的所有详情(如果需要完全覆盖)
// detailRepository.deleteByPlanId(planId);
// 或者采用逐个保存/更新(这里我们采用逐个保存/更新,避免全删全插带来的性能问题)
for (ProductionPlanDetailDTO dto : details) {
// 根据唯一键(planId和dateStr)查找是否已存在
Optional<ProductionPlanDetail> existing = detailRepository.findByPlanIdAndDateStr(planId, dto.getDateStr());
ProductionPlanDetail detail;
if (existing.isPresent()) {
detail = existing.get();
detail.setPlannedQuantity(dto.getPlannedQuantity());
detail.setActualQuantity(dto.getActualQuantity());
} else {
detail = new ProductionPlanDetail();
detail.setPlanId(planId);
detail.setDateStr(dto.getDateStr());
detail.setPlannedQuantity(dto.getPlannedQuantity());
detail.setActualQuantity(dto.getActualQuantity());
}
detailRepository.save(detail);
}
}
// 获取某个计划的所有详情
public List<ProductionPlanDetailDTO> getDetailsByPlanId(Long planId) {
List<ProductionPlanDetail> details = detailRepository.findByPlanId(planId);
return details.stream().map(detail -> {
ProductionPlanDetailDTO dto = new ProductionPlanDetailDTO();
dto.setDateStr(detail.getDateStr());
dto.setPlannedQuantity(detail.getPlannedQuantity());
dto.setActualQuantity(detail.getActualQuantity());
return dto;
}).collect(Collectors.toList());
}
}
```
4. DTO类
```java
@Data
public class ProductionPlanDetailDTO {
private String dateStr; // 日期字符串,格式:yyyy-MM-dd
private Integer plannedQuantity; // 计划交付数量
private Integer actualQuantity; // 实际交付数量
}
```
5. 控制器Controller
```java
@RestController
@RequestMapping("/api/production_plans/{planId}/details")
@RequiredArgsConstructor
public class ProductionPlanDetailController {
private final ProductionPlanDetailService detailService;
// 保存详情
@PostMapping
public ResponseEntity<?> saveDetails(@PathVariable Long planId, @RequestBody List<ProductionPlanDetailDTO> details) {
detailService.saveDetails(planId, details);
return ResponseEntity.ok().build();
}
// 获取详情
@GetMapping
public ResponseEntity<List<ProductionPlanDetailDTO>> getDetails(@PathVariable Long planId) {
List<ProductionPlanDetailDTO> details = detailService.getDetailsByPlanId(planId);
return ResponseEntity.ok(details);
}
}
```
三、前端调用
前端在点击“保存”按钮时,会收集表格中所有的输入框数据,然后按照以下格式组织:
```javascript
[
{ dateStr: "2024-06-01", plannedQuantity: 100, actualQuantity: 90 },
{ dateStr: "2024-06-02", plannedQuantity: 120, actualQuantity: 0 },
// ... 其他日期
]
```
然后调用保存接口:`POST /api/production_plans/{planId}/details`
注意:planId是当前生产计划的ID。
四、为什么这样设计能保证日期不变?
1. 我们使用字符串存储日期,而不是数据库的日期类型。这样存储的值就是固定的字符串,不会因为数据库的日期格式设置或时区问题而改变。
2. 在保存时,前端传递的是已经格式化好的字符串(如"2024-06-01"),后端直接存储这个字符串。
3. 在查询时,返回的也是这个字符串,所以每次显示的都是当初保存的日期字符串。
五、其他注意事项
1. 日期格式:前端和后端统一使用"yyyy-MM-dd"格式。
2. 唯一性约束:避免同一天保存多条记录,所以使用(plan_id, date_str)作为唯一键。
3. 性能考虑:如果每天的数据量很大(比如30天),那么每次保存时可能会进行30次查询和30次保存操作。如果担心性能,可以改为批量操作(先查询出该计划下所有的详情,然后在内存中匹配更新,最后批量保存)。但考虑到30条数据量不大,当前设计已经足够。
六、批量保存优化(可选)
如果希望提高性能,可以修改Service中的保存逻辑,改为批量处理:
```java
@Transactional
public void saveDetails(Long planId, List<ProductionPlanDetailDTO> details) {
// 获取该计划下所有的已有详情
List<ProductionPlanDetail> existingDetails = detailRepository.findByPlanId(planId);
Map<String, ProductionPlanDetail> existingMap = existingDetails.stream()
.collect(Collectors.toMap(ProductionPlanDetail::getDateStr, Function.identity()));
List<ProductionPlanDetail> toSave = new ArrayList<>();
for (ProductionPlanDetailDTO dto : details) {
ProductionPlanDetail detail;
if (existingMap.containsKey(dto.getDateStr())) {
detail = existingMap.get(dto.getDateStr());
detail.setPlannedQuantity(dto.getPlannedQuantity());
detail.setActualQuantity(dto.getActualQuantity());
} else {
detail = new ProductionPlanDetail();
detail.setPlanId(planId);
detail.setDateStr(dto.getDateStr());
detail.setPlannedQuantity(dto.getPlannedQuantity());
detail.setActualQuantity(dto.getActualQuantity());
}
toSave.add(detail);
}
detailRepository.saveAll(toSave);
}
```
这样就将多次数据库操作减少为两次(一次查询,一次批量保存)。
七、接口安全性
可以根据需要添加权限校验,例如只有管理员或有权限的用户才能保存详情。
八、测试
编写单元测试和集成测试确保功能正确。
总结:通过将日期存储为字符串,我们确保了保存后的日期不会变化。后端接口设计为接收一个日期字符串列表,每个字符串对应一天的数据,然后保存到数据库中。查询时返回的也是同样的字符串,从而保证了日期的固定不变。</think>### 后端接口实现:生产计划详情数据持久化存储(日期固定方案)
#### 核心设计思路
1. **日期固化机制**:将日期存储为不可变的字符串格式而非动态计算的日期类型
2. **双重存储策略**:
- `original_date`:存储原始日期值(用于审计)
- `fixed_date`:存储固化后的字符串日期(业务使用)
3. **数据不变性**:保存后禁止修改日期字段
#### 数据库表设计
```sql
CREATE TABLE production_plan_details (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
plan_id BIGINT NOT NULL COMMENT '关联的生产计划ID',
original_date DATE NOT NULL COMMENT '原始日期',
fixed_date CHAR(10) NOT NULL COMMENT '固化日期(YYYY-MM-DD)',
planned_quantity INT NOT NULL DEFAULT 0 COMMENT '计划交付量',
actual_quantity INT NOT NULL DEFAULT 0 COMMENT '实际交付量',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_plan_date (plan_id, fixed_date)
) COMMENT '生产计划详情表';
```
#### Spring Boot 实现代码
##### 1. 实体类设计
```java
@Entity
@Table(name = "production_plan_details")
public class ProductionPlanDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "plan_id", nullable = false)
private Long planId;
@Column(name = "original_date", nullable = false)
private LocalDate originalDate;
@Column(name = "fixed_date", nullable = false, length = 10)
private String fixedDate;
@Column(name = "planned_quantity", nullable = false)
private Integer plannedQuantity = 0;
@Column(name = "actual_quantity", nullable = false)
private Integer actualQuantity = 0;
// Getter/Setter省略
}
```
##### 2. 日期固化服务
```java
@Service
public class DateFixationService {
// 日期固化方法
public String fixDate(LocalDate date) {
return date.format(DateTimeFormatter.ISO_DATE); // 转为YYYY-MM-DD
}
// 批量日期固化
public Map<LocalDate, String> fixDates(List<LocalDate> dates) {
return dates.stream()
.collect(Collectors.toMap(
Function.identity(),
this::fixDate
));
}
}
```
##### 3. 详情保存接口
```java
@RestController
@RequestMapping("/api/production_plans/{planId}/details")
public class ProductionPlanDetailController {
private final DetailRepository detailRepository;
private final DateFixationService dateFixationService;
// 保存详情数据
@PostMapping
public ResponseEntity<?> saveDetails(
@PathVariable Long planId,
@RequestBody List<DetailDTO> details) {
// 1. 提取所有日期并固化
List<LocalDate> dates = details.stream()
.map(DetailDTO::getDate)
.collect(Collectors.toList());
Map<LocalDate, String> fixedDates = dateFixationService.fixDates(dates);
// 2. 转换为实体并保存
List<ProductionPlanDetail> entities = details.stream()
.map(dto -> {
ProductionPlanDetail entity = new ProductionPlanDetail();
entity.setPlanId(planId);
entity.setOriginalDate(dto.getDate());
entity.setFixedDate(fixedDates.get(dto.getDate()));
entity.setPlannedQuantity(dto.getPlannedQuantity());
entity.setActualQuantity(dto.getActualQuantity());
return entity;
})
.collect(Collectors.toList());
detailRepository.saveAll(entities);
return ResponseEntity.ok("保存成功");
}
// 详情查询接口
@GetMapping
public ResponseEntity<List<DetailDTO>> getDetails(
@PathVariable Long planId) {
List<ProductionPlanDetail> details = detailRepository.findByPlanId(planId);
List<DetailDTO> response = details.stream()
.map(entity -> new DetailDTO(
entity.getFixedDate(), // 返回固化日期
entity.getPlannedQuantity(),
entity.getActualQuantity()
))
.collect(Collectors.toList());
return ResponseEntity.ok(response);
}
// DTO定义
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class DetailDTO {
private String date; // 使用String类型
private Integer plannedQuantity;
private Integer actualQuantity;
}
}
```
#### 关键特性说明
1. **日期固化流程**:
```mermaid
sequenceDiagram
前端->>后端: 提交详情数据(含日期)
后端->>DateFixationService: 调用fixDate()
DateFixationService->>后端: 返回YYYY-MM-DD字符串
后端->>数据库: 保存fixed_date字段
```
2. **数据不变性保障**:
```java
@PreUpdate
public void preventDateUpdate(ProductionPlanDetail entity) {
// 禁止修改固化日期
ProductionPlanDetail original = detailRepository.findById(entity.getId()).get();
if (!original.getFixedDate().equals(entity.getFixedDate())) {
throw new IllegalStateException("固化日期不可修改");
}
}
```
3. **时区处理方案**:
```java
@Configuration
public class DateTimeConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.timeZone(TimeZone.getTimeZone("UTC"));
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ISO_DATE));
};
}
}
```
#### 前端调用示例
```javascript
async function saveDetail() {
const payload = [];
const inputs = document.querySelectorAll('#detailTable input');
inputs.forEach(input => {
payload.push({
date: input.dataset.date, // 如"2023-06-15"
plannedQuantity: parseInt(document.querySelector(`input[data-date="${input.dataset.date}"][data-type="planned"]`).value) || 0,
actualQuantity: parseInt(document.querySelector(`input[data-date="${input.dataset.date}"][data-type="actual"]`).value) || 0
});
});
try {
const response = await fetch(`/api/production_plans/${curDetailPlanId}/details`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
if (response.ok) {
alert('详情保存成功!');
}
} catch (error) {
console.error('保存失败:', error);
}
}
```
#### 设计优势
1. **日期不变性**:
- 使用`CHAR(10)`存储固定格式日期
- 保存后不再随系统时间变化
2. **数据追溯**:
- 同时保留原始日期(`original_date`)和固化日期(`fixed_date`)
- 支持历史数据审计
3. **查询优化**:
```sql
SELECT * FROM production_plan_details
WHERE fixed_date BETWEEN '2023-06-01' AND '2023-06-30' -- 字符串比较
```
4. **兼容性**:
- 前端无需修改日期处理逻辑
- 后端自动完成转换和验证
#### 性能优化建议
1. **批量操作**:
```java
@Transactional
public void batchSave(List<ProductionPlanDetail> entities) {
int batchSize = 50;
for (int i = 0; i < entities.size(); i += batchSize) {
List<ProductionPlanDetail> batch = entities.subList(i, Math.min(i + batchSize, entities.size()));
detailRepository.saveAll(batch);
}
}
```
2. **缓存策略**:
```java
@Cacheable(value = "planDetails", key = "#planId")
public List<ProductionPlanDetail> getByPlanId(Long planId) {
return detailRepository.findByPlanId(planId);
}
```
3. **索引优化**:
```sql
CREATE INDEX idx_fixed_date ON production_plan_details(fixed_date);
CREATE INDEX idx_plan_fixed_date ON production_plan_details(plan_id, fixed_date);
```
此方案确保保存的日期字段固定不变,同时保持系统的高性能和可维护性,符合生产计划管理的核心需求[^1][^3]。
阅读全文
相关推荐

















