我正在使用Spring中的REST api,我需要使用协议号保存实体Document
,其中包括:
progressiveInt/currentyear
这是模型:
@Entity
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String protocolNumber;
}
我想出了这个解决方案:
public void saveDocument(Document document) {
Document savedDoc = documentRepository.save(document);
int year = Calendar.getInstance().get(Calendar.YEAR);
String protocolNumber = savedDoc.getId() + "/" + year;
savedDoc.setProtocolNumber(protocolNumber);
documentRepository.save(savedDoc);
}
换句话说,我正在保存对象并使用DB创建的id更新它,但我想知道是否有更好的方法来执行此操作。
有人可以帮忙吗?
要使代码更清洁,你可以使用@PostPersist
,所以在你的Document
中添加如下方法:
@PostPersist
private void postPersist() {
int year = Calendar.getInstance().get(Calendar.YEAR);
this.protocolNumber = this.getId() + "/" + year ;
}
此更新后,您不需要再次保存/保留实例。所以如果你真的需要将protocolNumber
存储在数据库中。
但是:这个protocolNumber
也是一种瞬态值,所以你可能想要考虑在你的year
中只添加字段Document
,删除字段protocolNumber
并创建一个吸气剂,如:
public String getProtocolNumber() {
return this.id + "/" + this.year;
}
这样你就不需要知道持久的id
了。