How to cast into a custom @Type (PersistentDateTime) in Hibernate?

375 views Asked by At

I have mapped the statusDate field to org.joda.time.DateTime in the Foo class as follows:

@Column(name = "STATUSDATE", nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime statusDate = null;

I append the following subselect in the query (the where clause is really simplified for the sake of this question) and the value is sent through the constructor into an existing constructor matching org.joda.time.DateTime for such a field:

sb.append(", (select foo.statusDate from Foo foo where foo.id = :p_fooId) as fooStatusDate");

So far so good. However, there is a case I have a condition where I need to select null as the correct type instead.

sb.append(", (cast null as <customType>) as fooStatusDate");

This does not work as I cannot find how to cast correctly so the CustomType would be matched. My attempts and their results:

  1. These result in an inappropriate constructor error. Though I can create a constructor to handle this type and parse if not null, I prefer correct casting:

    • cast (null as string) results in Hibernate's StringType.
    • cast (null as timestamp) results in Hibernate's TimestampType.
    • cast (null as date) results in Hibernate's DateType.
    java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: 
    Unable to locate appropriate constructor on class
    
  2. These result in null and then fail on NPE as the type is not recognized:

    • cast (null as localdate) results in null.
    • cast (null as persistentdatetime) results in null.
    java.lang.NullPointerException
     at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:355)
     at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:180)
    
  3. Finally, this one doesn't even result in a parseable query:

    • cast (null as org.jadira.usertype.dateandtime.joda.PersistentDateTime) isn't even parsed.
    java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: 
    expecting CLOSE, found '.' near line 1, column 180
    

How to achieve a CustomType defined by PersistentLocalDate? I must use Spring 4.1.7, Hibernate 4.2.5, and Java 7 on this project. Though I am stuck with the mentioned versions, all answers for newer versions are welcome as well! (I upvote these, but do not mark them as accepted.)

The screenshot is from debug breakpoint of the CustomType I need at ReflectHelper, method public static Constructor getConstructor(Class clazz, Type[] types):

enter image description here

0

There are 0 answers