'How can I set variable annotated with @Transient form a setter of non transient variable in spring JPA?

I am trying to set the time variable while the Date and Time variable is getting initialized by spring JPA but I am getting null in the time string. How should I approach this problem ?

@Entity
@Table(name = "cap_ratio")
public class CapacitiveInfoModel {
    @Id
    @Column(name = "time")
    private Date dateAndTime;
    @Transient
    private String time;

    public Date getDateAndTime() {
        return dateAndTime;
    }
    public void setDateAndTime(Date dateAndTime) {
        this.dateAndTime = dateAndTime;
        this.time = DateAndTimeUtil.getFormattedDateAndTimeString(dateAndTime, "HH:mm");
    }
    public String getTime() {
        return time;
    }
}


Solution 1:[1]

you can try this code:

@Entity
@Table(name = "cap_ratio")
public class CapacitiveInfoModel {
    @Id
    @Column(name = "time")
    private Date dateAndTime;
    @Transient
    private String time;

    public Date getDateAndTime() {
        return dateAndTime;
    }
    public void setDateAndTime(Date dateAndTime) {
        this.dateAndTime = dateAndTime;
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        this.time = dateFormat.format(this.dateAndTime);
    }
    public String getTime() {
        return time;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rg226965