Spring+Hibernate+MySQL新增数据时出现额外全空记录如何解决
问题根因
你目前的代码存在两个核心错误导致空生产商记录生成:
- Controller的
saveExc方法中额外声明了@ModelAttribute("manufacturer") Manufacturer manufacturer参数,该参数没有对应表单字段绑定,拿到的永远是所有属性为空的Manufacturer对象,你主动调用了manufacturerService.saveOrUpdate将这个空对象存入了数据库。 - 你没有维护两个实体的双向关联关系,就算是正常新建场景,关联关系也不会自动生效。
修复方案
1. 修正Controller逻辑
修改addForm方法
不需要单独向Model中添加Manufacturer对象,直接绑定到成分对象的关联属性即可:
@GetMapping("/addExcipientForm") public String addForm(Model model){ ExcipientIngredient excipientIngredient = new ExcipientIngredient(); excipientIngredient.setManufacturer(new Manufacturer()); model.addAttribute("excipientIngredient", excipientIngredient); return "add-excipient-form"; }
修改saveExc方法
删除多余的空Manufacturer参数,保存前先维护双向关联,利用级联规则自动保存生产商,不需要单独调用生产商的保存方法:
@PostMapping("/saveExc") public String saveExcipients(@ModelAttribute("excipientIngredient") ExcipientIngredient excipientIngredient) { Manufacturer manufacturer = excipientIngredient.getManufacturer(); // 校验必填字段,避免空数据入库,可根据业务调整校验规则 if(manufacturer == null || manufacturer.getManName() == null || manufacturer.getManName().trim().isEmpty()){ throw new IllegalArgumentException("生产商名称不能为空"); } // 新建场景维护双向关联 if(manufacturer.getManId() == 0){ if(manufacturer.getExcipientIngredients() == null){ manufacturer.setExcipientIngredients(new ArrayList<>()); } manufacturer.getExcipientIngredients().add(excipientIngredient); } // 级联规则已配置PERSIST、MERGE,保存成分会自动同步生产商数据 excipientIngredientService.saveOrUpdate(excipientIngredient); return "redirect:/excipients/listExc"; }
2. 修正Thymeleaf表单绑定
所有生产商相关的输入框,th:field属性统一绑定到*{manufacturer.xxx},示例:
<!-- 生产商名称输入框示例 --> <div class="form-group"> <label>生产商名称</label> <input type="text" th:field="*{manufacturer.manName}" class="form-control" required> </div> <!-- 其他生产商字段以此类推,不要出现单独绑定*{manName}等脱离excipientIngredient的写法 -->
3. 数据库层增加非空约束(可选但推荐)
给Manufacturer实体的必填字段加上非空限制,避免非法数据入库:
@Column(name="name", nullable = false) private String manName; @Column(name="country", nullable = false) private String country; // 其他必填字段同理添加nullable = false
通用排查方向
如果修改后仍有问题,可按以下步骤定位:
- 开启Hibernate SQL日志,配置
spring.jpa.show-sql=true、spring.jpa.properties.hibernate.format_sql=true,观察执行的INSERT语句数量和参数,定位空记录是哪次插入生成的 - 在
saveExc方法入口打断点,查看excipientIngredient.getManufacturer()的所有属性值是否符合预期 - 如果业务支持选择已有生产商,需额外新增逻辑:根据前端传的生产商ID先查询数据库,存在则复用已有对象,避免重复创建
内容的提问来源于stack exchange,提问作者Stone
相关产品推荐
相关产品推荐

