kota srinu
kota srinu

Reputation: 49

Date conversion in Java Hibernate

i have one Date field to save date into DB and date field should be in Date and Time format (MM/dd/yyyy HH:mm:ss).. for that i am using DateFormat to convert the current Date as,

 DateFormat dateFormat  = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
         Date date = new Date();
         String DateStr = dateFormat.format(date);

Here the result will be in String format and to save as Date object in DB using Hibernate i have to again convert that date string into Date obj as,

Date newdate = dateFormat.parse(DateStr);

So my question was, is there any better way to return the current Date along with Time as Date obj.. and also does Hibernate will automatically convert the String to Date, if we set the field type as String and by annotating as,

@Temporal(TemporalType.DATE)
  @Column(name = "REQUESTED_DATE")
  public String getRequestedDate() {
        return requestedDate;
    }

thanks.

Upvotes: 1

Views: 9863

Answers (3)

Subrata nath
Subrata nath

Reputation: 172

@Temporal(value = TemporalType.TIMESTAMP)
Date date;

you can store date object directly into database that hibernate offers you. So, lets get rid of string.

Upvotes: 0

riddle_me_this
riddle_me_this

Reputation: 9145

Change your annotation to:

@Temporal(TemporalType.TIMESTAMP)

This will persist the time to the DB.

Upvotes: 1

Lew Bloch
Lew Bloch

Reputation: 3433

You can use java.sql.Date to store values that map to SQL DATETIME (or the MySQL variant). I do not understand why you say "by using new Date(),i [sic] will be getting only date not time". That is not correct. However, it is not optimal. You can also use java.sql.Timestamp. You get the best results when you use java.util.Calendar.

I found http://www.developerscrappad.com/228/java/java-ee/ejb3-jpa-dealing-with-date-time-and-timestamp/ in less than five minutes of Googling, and it answers your question pretty well.

Upvotes: 0

Related Questions