2

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.

2
  • 1
    What errors do you get? Why do you need a Timestamp object (instead of a java.util.Date) Commented Mar 13, 2013 at 15:13
  • It's not necessary to use Timestamp actually. I simply need to keep date and time informations in both side (Mysql <-> Java) Commented Mar 13, 2013 at 15:22

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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;
}

2 Comments

I got this error: Exception in thread "main" org.hibernate.exception.DataException: Data truncation: Incorrect datetime value: '' for column 'date' at row 1.....
Are you sure the column in the database is TIMESTAMP, not DATETIME?

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.