Hibernate parameter set with functions

When using hibernate, it can usually figure out the type of your parameters by looking at either the property it is against, or hibernate, it seems to recognize certain types by default (like java.util.Date).

However, I have several queries that use (dateadd) functions. These requests use an object that does not have a custom type binding (hibernation, by default, does not have a BINARY value when it cannot determine the type). I have to pass the correct hibernate "Type" in relation to the request parameter.

This will result in an error

        Query query = session.createQuery( hql );
        query.setParameter( "now", new LocalDateTime() );
        return query.list();

      

This will work (type explicitly set)

        Query query = session.createQuery( hql );
        query.setParameter( "now", new LocalDateTime(), Hibernate.custom( LocalDateTimeType.class ) );
        return query.list();

      

This will also work (using java.util.Date)

        Query query = session.createQuery( hql );
        query.setParameter( "now", new Date() );
        return query.list();

      

Is there a way to get Hibernate to recognize LocalDateTime as a type that it can handle out of the box, without having to worry about passing that type explicitly every time?

Thanks.

+2


a source to share


2 answers


Answering my own question.

This is apparently impossible. There is a multi-year feature request (5 1/2 years and counting) on ​​this.

Hibernate JIRA



If you want to be a complete hacker, you can use some nasty thinking to get it done. I do not recommend this as it relies on inspecting internals of both Hibernate and the JDK's implementation of UnmodifiableMap.

    // HACK ALERT!!
    Field field = TypeFactory.class.getDeclaredField( "BASIC_TYPES" );
    field.setAccessible( true );
    Map basicTypes = (Map)field.get( null );

    field = basicTypes.getClass().getDeclaredField( "m" );
    field.setAccessible( true );
    Map underlyingMap = (Map)field.get( basicTypes );

    underlyingMap.put( SomeType.class.getName(), Hibernate.custom( MyCustomUserType.class ) );

      

0


a source


0


a source







All Articles