Reputation: 49
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
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
Reputation: 9145
Change your annotation to:
@Temporal(TemporalType.TIMESTAMP)
This will persist the time to the DB.
Upvotes: 1
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