Search code examples
javajpahibernate-mapping

Date calculation in Entity


I have my entity class like this

 @Entity
 public class CheckInstrument extends BaseEntity {
    public CheckInstrument() {
    }
    @Column(nullable = false)
    private Date currentCheck;
    @Column(nullable = false)
    private Long periodicity;
    @Column
    private Date nextCheck;
    @Column
    private boolean isExpired;`

    (getters and setters)

My issues is

  1. Сalculate nextCheck such as adding periodicity(month) to currentCheck
  2. Calculate isChecked property as comparing nextCheck with current System Date.

Solution

  • I think your question is a pure date calculation problem, has nothing to do with Hibernate or jpa entity.

    all codes are not written in IDE, not tested either:

    • Calculate nextCheck such as adding periodicity(month) to currentCheck

    You may want to check the Calendar class

    Calendar cal = Calendar.getInstance();
    cal.setTime(currentCheck);
    cal.add(Calendar.MONTH,1);
    currentCheck = cal.getTime();
    
    • Calculate isChecked property as comparing nextCheck with current System Date.

    java.util.Date implements Comparable, so you can compare two dates like:

    int result = date1.compareTo(date2);
    

    To your question: nextCheck.compareTo(new Date())

    IMO, isExpired / overdued shouldn't be added as database field. because it is related current date. It would be better to get that flag by calculation, to make it real time. Well it is anyway up to your requirement.