【发布时间】:2019-03-17 13:00:48
【问题描述】:
我正在使用 Spring Boot 2(Hibernate、JPA)和 MySQL。我需要一个唯一的、自动递增的自定义参考编号,例如 18/10/5(这里,18 是年,10 是月,5 是自动递增字段)。我使用的策略是:
创建一个自动递增字段。保存并加入yy/MM/后获取自增的值。
为方便起见,我删除了不需要的注释。
模型类
@Entity
@Table(name="account")
public class Account{
@Id
private String id;
@GeneratedValue(strategy=GenerationType.AUTO)
private Long autoIncrement;
String refNo;
//Other fields, Constructors, Getters And Setters
}
然后在控制器中,首先我保存,然后我获取保存对象的 id 并尝试更新
控制器类
@RestController
@RequestMapping("/account")
public class AccountController {
@PostMapping("/save")
public ModelAndView saveAccount(@ModelAttribute("account") Account account){
//few codes
accountService.save(account) //Saving
accountService.updateRefNo(account.getId()) //try to update
}
}
服务类
@Service
@Transactional
public class AccountServiceImpl implements AccountService{
@Autowired
AccountRepository accountRepository;
//Few methods
public void updateRefNo(String id) {
Account account=findById(id); // return the object
String year = // getting year
String month = //getting month
account.setRefNo(year+"/"+month+"/"+account.getAutoIncrement());
}
}
数据已保存。当我尝试更新时,account.getAutoIncrement() 返回 null,但它保存在数据库中。我也试过saveAndFlush()。为什么会这样?没有承诺?
【问题讨论】:
-
该帐户是新帐户吗?并且是客户提供的帐户ID吗?我通常看到的代码在保存时会生成 id。如果您的代码也是如此,您不使用 null 调用您的 updateRefNo 方法,因为您不使用保存返回的 id 吗?
标签: mysql spring hibernate spring-boot spring-data-jpa