Issue
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?
Solution
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();
}
Answered By - Eklavya