Site icon NgDeveloper

Understanding @Temporal and @JsonFormat in JPA Hibernate

Understanding @Temporal and @JsonFormat in JPA Hibernate

Many of us prefer to use varchar even for date fields due to difficulty of date related db operations. But it is strongly not recommended to use varchar for date fields and highly advicable to use datetime or timestamp in MySQL.

Today we are going to see how to use datetime field with hibernate, also it displays date and time, but I want to display only date in UI. So lets see what should be done for this requirement.

 

 

What is @Temporal?

@Temporal is a JPA annotation used to store either TIME, DATE or TIMESTAMP in database table. Format can be defined using TemporalType. DATE, TIME AND TIMESTAMP are available temporaltypes.

By default date field maps to sql.date but util.date is highly recommended in java to perform date operations. @Temporal does this job very nicely.

 

 

Hibernate Entity class:

Here couponStartDate field is annotated with @Temporal with temporaltype as timestamp.

And couponcount is annotated with @Transient and this field is actually does not need have equivalent column in db, also due to transient it will not be serialized as well.

I have added @JsonFormat annotation for couponStartDate and couponEndDate fields because if you do not annotate then this will return the date in milliseconds. So I am specifying the format during select time with pattern attribute (dd-MM-yyyy).

[java]
@Entity
public class Coupon implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name=”coupon_id”)
private Long couponId;

private String couponTitle;

@Column(columnDefinition = “varchar(500)”)
private String couponDesc;

@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(pattern=”dd-MM-yyyy”)
@Column(name=”coupon_start_date”)
private Date couponStartDate;

@Column(name=”coupon_end_date”)
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(pattern=”dd-MM-yyyy”)
private Date couponEndDate;

@Transient
private Long couponcount;

}

[/java]

 

During retrieval date will be returned in milliseconds which is converted here to dd-mm-yyyy using @JsonFormat annotation.

During Saving full timestamp will be saved due to temporalType timestamp.

 

 

Exit mobile version