4

I am storing date in mysql database using field of type DATE :

@Temporal(TemporalType.DATE)
@Column(name="RECIEVING_DATE")
private Date recieving_date;

// getters and setters

but when hibernate saves it , date is saved in type of datetime format, i.e. it doesn't store just 2015-02-23 but 2015-02-23 00:00:00.

The code I am using for inserting the date

String recieving_date = request.getParameter("recieving_date");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    java.sql.Date ds = null;
    try {
        Date date = df.parse(recieving_date);
        ds=new java.sql.Date(date.getTime());
    } catch (ParseException e1) {
        System.out.println("Exception occured in parsing date : "+e1);
    }
    doc_mvmnt.setRecieving_date(ds); 

Now , I can change type by running alter table query myself in database , but that will be painful every time. How can I tell hibernate to keep the type I want . And further , if this is possible , is it possible to define the size of varchar and integers using hibernate. Please help

4
  • how do you set date value for recieving_date, plz show the code related to date you set for it Commented Feb 22, 2015 at 22:40
  • I edited the post !! please see if you can help Commented Feb 22, 2015 at 22:48
  • Possible duplicate of stackoverflow.com/questions/22785117/… Commented Feb 22, 2015 at 23:39
  • no, I am trying using just hibernate Commented Feb 22, 2015 at 23:40

1 Answer 1

1

as I see you are passing only date part of datetime to the recieving_date and surely the type of recieving_date is java.sql.Date (as you passing date of that type to it) so I think one of these annotations should work @Type(type="date") or @Temporal(TemporalType.DATE) and as the second one does not work try the other and give a feedback:

@Column(name="RECIEVING_DATE")
@Type(type="date")
private Date recieving_date;

// getters and setters

if this does not solve the issue then try with modifying the getters and setters for your custom format

Sign up to request clarification or add additional context in comments.

5 Comments

this Type annotation belongs to which package ??
org.hibernate.annotations.Type
you are very welcome, glad to see the issue has fixed.
can I use this annotation to also specify length of varchar or integers. Is there any annotation to do that ?? because by default it gives 255 chars , what if I dont want to keep that size , may be increase it or decrease to 100 chars
for length of string you can use length attribute of @Column (for length of column) annotation. you can also use the max attribute of @Size annotation (for forcing the length of value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.