EdgeCase
EdgeCase

Reputation: 4827

Two Java Dates have Different Formats

I have an entity class that represents an object brought over from MySQL. One of the fields is a MySQL DateTime field that I've mapped via Hibernate as

@Temporal(TemporalType.DATE)
private Date effdate;

However, if that date happens to be null from the database, I want to set it to the current date in the setter method. As I understand it, Hibernate does not support defaults, and to default the field with a columnDefinition clause would tie the implementation to a vendor.

When the field is properly populated in MySQL it looks like the 2nd output line. When I default it, it looks like the first. Shouldn't two date fields look the same? If it won't be a problem in the end, I won't worry about it, but I'd like to understand how a Date object can appear differently. I am aware of SimpleDateFormat, but not sure if it's coming into play here, since both are just date objects. Is the @Temporal annotation doing something to it?

Tue Apr 24 14:34:10 EDT 2012  <- my default
2012-04-24 00:00:00.0         <- from MySQL

The setter method

public void setEffdate(Date effdate) {
// TODO if effdate is null use "d"

    Date d = new Date();
    this.effdate = effdate;

    System.out.println(d);
    System.out.println(this.effdate + "\n");

Upvotes: 0

Views: 141

Answers (2)

NPE
NPE

Reputation: 500347

I'd like to understand how a Date object can appear differently

There are two concrete classes called Date: java.util.Date and java.sql.Date. The latter extends the former and formats the date as "2012-04-24".

both are just date objects

They are almost certainly instances of the two different types, which explains the difference in behaviour. The one you're getting from MySQL is probably java.sql.Date and the default one you're creating yourself is probably java.util.Date.

Upvotes: 1

jambriz
jambriz

Reputation: 1303

what about using the coalesce function to specify default from the database and not in java ?

http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce

otherwise aix is right, you should check your imports

Upvotes: 0

Related Questions