简体   繁体   中英

hibernate - making type of column in mysql only date and not datetime

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, ie 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM