英文:
Is it possible to store a method return value in the database without having a corresponding attribute?
问题
让我们假设我有以下类。
@Entity
public class ShiftDetail {
@Id
private Integer id = null;
private String name = null;
private LocalTime startTime = null;
private LocalTime endTime = null;
public Duration getShifDurationInSeconds() {
return Duration.between(this.startTime, this.endTime).toSeconds();
}
}
为了使一些未来的处理更加方便,我想将派生值“ShiftDurationInSeconds”存储在数据库中。
是否可以在不在类中创建属性的情况下使用JPA/ Hibernate来实现这一点?
英文:
Let's say I have the following class.
@Entity
public class ShiftDetail {
@Id
private Integer id = null;
private String name = null;
private LocalTime startTime = null;
private LocalTime endTime = null;
public Duration getShifDurationInSeconds() {
return Duration.between(this.startTime, this.endTime).toSeconds();
}
}
For making some down-the-line processing easier, I would like to store the derived value "ShiftDurationInSeconds" in the database.
Is there a way to do this with JPA/ Hibernate without creating an attribute in the class?
答案1
得分: 2
你可以使用 @PreUpdate
和 @PrePersist
来在数据库中计算字段的持久性。
private long shiftDurationInSeconds;
@PreUpdate
@PrePersist
public void calShiftDurationInSeconds() {
shiftDurationInSeconds = Duration.between(this.startTime, this.endTime).getSeconds();
}
英文:
You can use @PreUpdate
and @PrePersist
for calculate field persist in database.
private long shiftDurationInSeconds;
@PreUpdate
@PrePersist
public void calShiftDurationInSeconds() {
shiftDurationInSeconds = Duration.between(this.startTime, this.endTime).getSeconds();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论