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).

public class Coupon implements Serializable{
@GeneratedValue(strategy = GenerationType.AUTO)
private Long couponId;

private String couponTitle;

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

private Date couponStartDate;

private Date couponEndDate;

private Long couponcount;



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.



1,390 total views, 6 views today

About Mirthbees 681 Articles
Blogger, Innovator, Developer and Enterpreneur. Founder of GuruRecharge, Readymade online recharge script. Lead Developer in Bookrate.in

Be the first to comment

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.