【问题标题】:Filtering a collection using the @Filter hibernate annotation in java在java中使用@Filter hibernate注解过滤集合
【发布时间】:2023-03-26 02:07:01
【问题描述】:

我有两个休眠映射实体 A 和 B。

A 有 2 个实体 B 集合,我想根据 B 中的属性过滤每个集合(如下面的代码所示)。

@FilterDefs()
class A{

@OneToMany(mappedBy = "productType", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Filter(name = "something", condition = "entityType = 'SKU1'")  
Set<B> set1 = new HashSet<B>();

@OneToMany(mappedBy = "productType", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Filter(name = "something", condition = "entityType = 'SKU2'")  
Set<B> set2 = new HashSet<B>();

 }

class B{

@ManyToOne(cascade = CascadeType.ALL)
private A productType;

@Column(name = "entity_type")
@Enumerated(EnumType.STRING)
private EntityType entityType;
}

编辑: 我在我的 DAO 方法中启用了如下建议的过滤器。但是,我收到以下异常

org.hibernate.exception.SQLGrammarException:无法初始化 收藏

如果我使用急切加载方法,我会遇到与生成无效 SQL 有关的异常吗?

任何指针?

【问题讨论】:

  • 你能添加更多的堆栈跟踪吗?

标签: hibernate


【解决方案1】:

我在实体中使用 FilterDef,然后在我想使用过滤器的集合中设置。在您的示例中:

class A{
@OneToMany(...)
@Filter(name = "filterName")  
Set<B> set2 = new HashSet<B>();
}

@FilterDef(name = "filterName", 
    defaultCondition = condition,
    parameters = {@ParamDef(name = nameParameter,
    type = typeParameter)})
class B{
}

然后正如 ssedano 所说,您应该在会话中启用过滤器:

session.enableFilter("filterName")

如果是的话,放上参数:

session.getEnabledFilter(filterName).setParameter(nameParameter,value);

【讨论】:

    【解决方案2】:

    您必须在 DAO 中启用过滤器。

    session.enableFilter("something");
    

    在检索对象之前。

    【讨论】:

    • 正如您所建议的,我在我的 DAO 中启用了过滤器,但出现以下异常:org.hibernate.HibernateException: No such filter configured [something].. 我需要创建一个 FilterDef 还是在其他地方添加条目?
    • 检查您的过滤器定义特别检查类型。您应该使用原始类型,例如字符串、整数、长整数和......如果您需要列表作为参数值发送,这一点很重要;你应该使用 setParameterList() 而不是 setParameter()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2015-10-14
    • 2016-08-01
    • 2019-04-03
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多