你可以在Hibernate过滤器中使用自定义对象吗?

时间:2010-03-10 15:43:22

标签: java hibernate

我有一个需要使用数据库中两个不同列进行评估的hibernate过滤器。我有另一个现有的hibernate对象,包含这两个字段,我希望能够将另一个hibernate对象传递给session.enableFilter.setParameter()调用,而不是分别传递它中包含的值。

具体来说,我想替换这段代码:

session
     .enableFilter("inLocation")
     .setParameter("traversalLeft", 5)
     .setParameter("traversalRight", 10);

使用此代码:

session
     .enableFilter("inLocation")
     .setParameter("location", locationHibernateObject)

更好地隔离过滤器需要什么。

但是当我尝试配置过滤器时:

@FilterDef(name="inLocation", parameters=@ParamDef( name="location", type="com.example.Location" ) )
@Filters( {
    @Filter(name="inLocation", condition="current_location_id in (select location.id from location where location.traversal_left between :location.traversalLeft+1 and :location.traversalRight)")
} )
public class ClassToFilter {

尝试调用enableFilter()

时出错

这是甚至可能的吗?我做错了什么?

1 个答案:

答案 0 :(得分:3)

我遇到了同样的问题。

我正在使用 hibernate-annotations-3.4.0.GA ,我的过滤器和自定义类型位于一个 package-info.java 文件中。使用该设置,问题似乎在:

  • org.hibernate.cfg.AnnotationBinder#bindPackage(),之前处理过滤器,而不是自定义类型之后。
  • org.hibernate.cfg.AnnotationBinder#bindFilterDef(),根本不会尝试发现自定义类型。

我更改了方法的调用顺序,并将bindFilterDef()中的调用替换为:

    private static void bindFilterDef(FilterDef defAnn, ExtendedMappings mappings) {
        Map params = new HashMap();
        for (ParamDef param : defAnn.parameters()) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////
            // support for custom types in filters
            params.put( param.name(), getType( param.type(), mappings ) );
        }
        FilterDefinition def = new FilterDefinition( defAnn.name(), defAnn.defaultCondition(), params );
        log.info( "Binding filter definition: {}", def.getFilterName() );
        mappings.addFilterDefinition( def );
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // support for custom types in filters
    private static org.hibernate.type.Type getType(String paramType, ExtendedMappings mappings) {
        org.hibernate.type.Type heuristicType = TypeFactory.heuristicType( paramType );
        if ( heuristicType == null ) {
            org.hibernate.mapping.TypeDef typeDef = mappings.getTypeDef(paramType);
            if ( typeDef != null ) {
                heuristicType = TypeFactory.heuristicType( typeDef.getTypeClass(), typeDef.getParameters() );
            }
        }
        log.debug( "for param type: {} parameter heuristic type : {}", paramType, heuristicType );
        return heuristicType;
    }

当然,我必须从头开始构建jar,但这种改变似乎解决了这个问题。

但是,在 Hibernate 3.5 中,注释类被捆绑在 hibernate3.jar 中,因此可能需要更多的工作,因为所有内容都必须从头开始构建。

相关问题