gpt4 book ai didi

java - jpa/hibernate 查询返回的实体中包含的过滤器列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:11 26 4
gpt4 key购买 nike

我有一个简单的 jpa 实体“ApplicationForm”,其中包含一对多列表:

 @OneToMany(cascade=CascadeType.REMOVE, mappedBy="textQuestion")
private List<Dictionary> questions;

ApplicationForm 中包含的变量 Dictionary 只是另一个普通实体,其中仅包含问题的文本。Dictionary映射对应的数据库表为:

'locale' 'text'      'formId'
en my question 123
it mia domanda 123

我想知道是否可以使用 jpa 或 hibernate 构建一个查询来检索具有特定区域设置(例如仅“it”)的字典的 ApplicationForm 实体。使用标准 sql 很容易做到这一点,但我无法用 hql 进行翻译。

如果不可能,您能建议其他方法吗?我尝试手动迭代字典问题列表并删除不需要的区域设置,但并不是很优雅,而且我还收到了 jpa/hibernate 错误。

我希望我已经说清楚了,提供的代码就足够了。

谢谢

最佳答案

I was wondering if it's possible with jpa or hibernate, to build a query for retrieving an ApplicationForm entity with a Dictionary for a specific locale, for example 'it' only.

不适用于标准 JPA。但 Hibernate 允许应用任意 filters给定 session 期间的集合负载。来自 Hibernate 注解引用指南:

2.4.8. Filters

Hibernate has the ability to apply arbitrary filters on top of your data. Those filters are applied at runtime on a given session. First, you need to define them.

@org.hibernate.annotations.FilterDef or @FilterDefs define filter definition(s) used by filter(s) using the same name. A filter definition has a name() and an array of parameters(). A parameter will allow you to adjust the behavior of the filter at runtime. Each parameter is defined by a @ParamDef which has a name and a type. You can also define a defaultCondition() parameter for a given @FilterDef to set the default condition to use when none are defined in each individual @Filter. A @FilterDef(s) can be defined at the class or package level.

We now need to define the SQL filter clause applied to either the entity load or the collection load. @Filter is used and placed either on the entity or the collection element

@Entity
@FilterDef(name="minLength", parameters=@ParamDef( name="minLength", type="integer" ) )
@Filters( {
@Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length"),
@Filter(name="minLength", condition=":minLength <= length")
} )
public class Forest { ... }

When the collection use an association table as a relational representation, you might want to apply the filter condition to the association table itself or to the target entity table. To apply the constraint on the target entity, use the regular @Filter annotation. However, if you wan to target the association table, use the @FilterJoinTable annotation.

@OneToMany
@JoinTable
//filter on the target entity table
@Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length")
//filter on the association table
@FilterJoinTable(name="security", condition=":userlevel >= requredLevel")
public Set<Forest> getForests() { ... }

另请参阅

关于java - jpa/hibernate 查询返回的实体中包含的过滤器列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8465182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com