Spring Boot JPA保存PrimaryAccount时报account_number cannot be null错误
问题根源&修复方案
你这个报错是多个层级的参数传递、参数绑定、赋值逻辑错误共同导致的,逐一修复即可:
1. 控制层没有把前端传入的参数传递给业务层
你在Controller的接口方法里已经拿到了Spring MVC待绑定的PrimaryAccount对象,但调用Service方法的时候完全没有把这个对象传进去,Service层拿不到前端传入的任何数据。
修复:- 先修改
AccountService接口,给createPrimaryAccount方法加入参:
public interface AccountService { ResponseEntity<String> createPrimaryAccount(PrimaryAccount primaryAccount); }- 再修改Controller的调用逻辑,加
@RequestBody注解让Spring把Post请求体的JSON绑定到实体类,同时把绑定好的参数传入Service:
@PostMapping("/primaryAccount") public ResponseEntity<String> primaryAccount(@RequestBody PrimaryAccount primaryAccount) { return accountService.createPrimaryAccount(primaryAccount); }- 先修改
2. 业务层赋值逻辑完全错误
你在Service实现类里新new了一个空的PrimaryAccount对象,然后把这个空对象自身的null属性值取出来又赋值给自身,存库当然会触发非空约束报错。
修复:直接用Controller传过来的填充好属性的对象存库即可:@Service public class AccountServiceImpl implements AccountService { @Autowired private PrimaryAccountDao primaryAccountDao; public ResponseEntity<String> createPrimaryAccount(PrimaryAccount primaryAccount) { primaryAccountDao.save(primaryAccount); return ResponseEntity.ok("Record entered"); } }3. Postman传参的JSON字段名和实体类属性不匹配
你实体类的属性是小驼峰命名accountNumber、accountBalance,但Postman里传的是首字母大写的AccountNumber、AccountBalance,Spring MVC做参数绑定的时候识别不了,就算前面的逻辑改了,拿到的属性还是null。
修复:把Postman的请求参数改成小驼峰即可:{ "accountNumber": "89000", "accountBalance": 2000.00 }4. 持久层方法参数类型不匹配(潜在问题)
你实体类里的accountNumber是String类型,但findByAccountNumber方法的入参写的是long,后续调用这个方法的时候会报类型不匹配错误,建议提前修复:public interface PrimaryAccountDao extends CrudRepository<PrimaryAccount, Long> { PrimaryAccount findByAccountNumber (String accountNumber); }
内容的提问来源于stack exchange,提问作者Seeschon
相关产品推荐
相关产品推荐

