mlemmy
mlemmy

Reputation: 93

Named query returns java.sql.Timestamp instead of java.util.Date

I'm using Hibernate 5.3.13

I am querying for a date with a named query:

    public Date getDate() {
        return entityManager.createNamedQuery("MyEntity.myNamedQuery", Date.class)
                            //setting some parameters here
                            .getSingleResult();
    }

Column definition:

    @Column(name="date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

This query works fine but hibernate returns java.sql.Timestamp when I want java.util.Date.

Is it possible to make hibernate return Date instead of Timestamp?

Upvotes: 1

Views: 1092

Answers (1)

akuzminykh
akuzminykh

Reputation: 4743

Taken from Hibernate – Mapping Date and Time:

As we've seen, the java.util.Date type (milliseconds precision) is not precise enough to handle the Timestamp value (nanoseconds precision).

So when we retrieve the entity from the database, we'll unsurprisingly find a java.sql.Timestamp instance in this field, even if we initially persisted a java.util.Date:

[...]

This should be fine for our code since Timestamp extends Date.

You can just cast the returned value to Date.

Check out the reference in general, it has more details for you.

Upvotes: 2

Related Questions