开发者

Hibernate parameter typing with functions

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

However I have some queries which use functions (dateadd). In these queries using a object that has a cus开发者_如何学JAVAtom type binding fails (hibernate seems to default it to BINARY when it can't figure out the type). I have to pass in the correct hibernate "Type" against the query parameter.

This will fail

        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 any way I can get Hibernate to recognise LocalDateTime as a type it can handle out of the box without having to remember to pass in the type explicitly each time?

Thanks.


This might help:

http://www.redhat.com/docs/en-US/JBoss_Hibernate/3.2.4.sp01.cp03/html/Reference_Guide/Hibernate_Types-Custom_value_types.html


Answering my own question.

This is apparently not possible. There is a long-standing feature request (5 1/2 years old and counting) on this.

Hibernate JIRA

If you want to be complete hacker you can use some nasty reflection to do this. I don't recommend this as it relies on inspecting the internals of both Hibernate and the implementation of UnmodifiableMap in the JDK.

    // 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜