CheckinListener
Spring JPA Annotations: @PrePersist and @PreUpdate
- Before any Checkin is saved across the CP app, the CheckinListener intercepts and calls the calculateTimeInClass method for the Checkin entity. Specifically, the beforeSave method (the name is not important) in the CheckinListener is invoked automatically by the persistence context right before a Checkin entity is either created (persisted) for the first time or updated.
- During these events, the calculateTimeInClass method on the Checkin object is called.
public class CheckinListener {
@PrePersist
@PreUpdate
public void beforeSave(Checkin checkin) {
checkin.calculateTimeInClass();
}
}
Note: "beforeSave" is NOT using a repository method prefix and can theoretically be named anything (as opposed to Spring JPA's "saveBy___" methods).
Checkin:
Taking Advantage of Instant to calculate Duration
- Because startTime and endTime are Instants, the Duration object (java.time.Duration) can be invoked to easily calculate time using Duration's built in getSeconds() method. Duration returns a long, we convert it to a BigInteger and set timeInClassInSeconds property:
public void calculateTimeInClass() {
if (startTime != null && endTime != null) {
long seconds = Duration.between(startTime, endTime).getSeconds();
setTimeInClassInSeconds(BigInteger.valueOf(seconds));
} else {
setTimeInClassInSeconds(BigInteger.ZERO);
}
}
- We place calculateTimeInClass within the Checkin entity as a practical design choice. This method acts as an implicit setter for timeInClassInSeconds, leveraging the direct availability of startTime and endTime within the same object. This is done to avoid unnecessary external dependencies, data manipulation, and unnecessary additional fetches to the repository (e.g. at the service level) when the same Checkin object is already present at hand when we set the endTime.
- In other words, we use endTime to kill two birds with one stone, and make it clear from the architecture of the code that timeInClassInSeconds is set automatically.
CheckinListener
Spring JPA Annotations: @PrePersist and @PreUpdate
Note: "beforeSave" is NOT using a repository method prefix and can theoretically be named anything (as opposed to Spring JPA's "saveBy___" methods).
Checkin:
Taking Advantage of Instant to calculate Duration