Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem persisting a java.util.Date into MySql using Hibernate

I've been debugging this problem for the last couple of hours with no success and figured I'd throw it out to SO and see where that goes.

I'm developing a Java program that persists data into a MySql database using Hibernate and the DAO/DTO pattern. In my database, I have a memberprofile table with a firstLoginDate column. In the database, the SQL type of that column is a DateTime. The corresponding section of the Hibernate XML file is

<property name="firstLoginDate" type="timestamp">
    <column name="firstLoginDate" sql-type="DATETIME"/>
</property>

However, when I try to save a Date into that table (in Java), the "date" (year/month/day) part is persisted correctly, but the "time of day" part (hours:minutes:seconds) is not. For instance, if I try to save a Java date representing 2009-09-01 14:02:23, what ends up in the database is instead 2009-09-01 00:00:00.

I've already confirmed that my own code isn't stomping on the time component; as far as I can see source code (while debugging) the time component remains correct. However, after committing changes, I can examine the relevant row using the MySql Query Browser (or just grabbing back out from the database in my Java code), and indeed the time component is missing. Any ideas?

I did try persisting a java.sql.Timestamp instead of a java.util.Date, but the problem remained. Also, I have a very similar column in another table that does not exhibit this behavior at all.

I expect you guys will have questions, so I'll edit this as needed. Thanks!


Edit @Nate:

...
MemberProfile mp = ...
Date now = new Date();
mp.setFirstLoginDate(now);
...

MemberProfile is pretty much a wrapper class for the DTO; setting the first login date sets a field of the DTO and then commits the changes.


Edit 2: It seems to only occur on my machine. I've already tried rebuilding the table schema and wiping out all of my local source and re-checking-out from CVS, with no improvement. Now I'm really stumped.


Edit 3: Completely wiping my MySql installation, reinstalling it, and restoring the database from a known good copy also did not fix the problem.

like image 558
Matt Ball Avatar asked Dec 29 '25 01:12

Matt Ball


1 Answers

I have a similar setup to you (except mine works), and my mapping file looks like this:

<property name="firstLoginDate" type="timestamp">
    <column name="firstLoginDate" length="19"/>
</property>

My database shows the column definition as datetime.

Edit:

Some more things to check...

  • Check that the mysql driver the same on your local as on the working machines.
  • Try dropping the table, and have hibernate recreate it for you. If that works, then there's a problem in the mapping.
like image 118
Jesse Avatar answered Dec 30 '25 15:12

Jesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!