简体   繁体   中英

Hibernate mapping MySQL DateTime

I've a table in a mysql db with the following schema: [ID, Value, Date] where ID and Value are int field and Date is a TIMESTAMP. I defined a Java class like this:

class myClass{
  private int ID;
  private int value;
  private java.sql.Timestamp date;
}

If I try to read records from the db using the map that I defined for Hibernate everything looks good, anyway if I create a new object and I try to insert it in my db I get errors. I read a lot of post about this but I'm really confused.

Use the java.util.Date class instead of java.sql.Date. Then it should look like this :

public class myClass {
     private int ID;
     private int value;

     @Temporal(TemporalType.TIMESTAMP)
     private java.util.date date;
}

You need to tell Hibernate (or JPA) what the column is. Different databases handle naked date fields differently. I know in Oracle, if you don't annotate the column, Oracle will make it an (Oracle) timestamp. Which may or may not be what you want and what it won't be is performant. I'd recommend always using an annotation and based on this question, it looks like you have to with mySQL.

Try this:

class myClass {
     private int ID;
     private int value;

     @Temporal(TemporalType.TIMESTAMP)
     private java.sql.Timestamp date;
}

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