Spring 为实体生成渐进式唯一整数
Spring generate progressive unique int for entity
我正在 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);
}
换句话说,我正在保存对象并使用数据库创建的 ID 更新它,但我想知道是否有更好的方法来执行此操作。
有人可以帮忙吗?
为了使代码更简洁,您可以使用 @PostPersist
,因此将如下所示的方法添加到您的 Document
:
@PostPersist
private void postPersist() {
int year = Calendar.getInstance().get(Calendar.YEAR);
this.protocolNumber = this.getId() + "/" + year ;
}
您应该不需要在这次更新后再次保存/保留实例。因此,如果您确实需要将 protocolNumber
存储在数据库中。
但是:这个 protocolNumber
也是一种临时值,因此您可能还需要考虑将字段 year
添加到您的 Document
中,删除字段 protocolNumber
和创建一个 getter 如:
public String getProtocolNumber() {
return this.id + "/" + this.year;
}
这样你就不需要知道 id
坚持了。
我正在 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);
}
换句话说,我正在保存对象并使用数据库创建的 ID 更新它,但我想知道是否有更好的方法来执行此操作。
有人可以帮忙吗?
为了使代码更简洁,您可以使用 @PostPersist
,因此将如下所示的方法添加到您的 Document
:
@PostPersist
private void postPersist() {
int year = Calendar.getInstance().get(Calendar.YEAR);
this.protocolNumber = this.getId() + "/" + year ;
}
您应该不需要在这次更新后再次保存/保留实例。因此,如果您确实需要将 protocolNumber
存储在数据库中。
但是:这个 protocolNumber
也是一种临时值,因此您可能还需要考虑将字段 year
添加到您的 Document
中,删除字段 protocolNumber
和创建一个 getter 如:
public String getProtocolNumber() {
return this.id + "/" + this.year;
}
这样你就不需要知道 id
坚持了。