[英]Hibernate: search for entities that contains a value in a set of enums
I have an entity similar to the following example: 我有一个类似于以下示例的实体:
@Entity
@Table(name = "AIRPLANE")
public class Airplane {
@ElementCollection(targetClass = Color.class, fetch = FetchType.LAZY)
@CollectionTable(name = "AIRPLANE_COLORS", joinColumns = @JoinColumn(name = "AIRPLANE_ID"))
@Column(name = "AIRPLANE_COLOR")
@ForeignKey(name = "FK_AIRPLANE_COLOR_ID")
@Enumerated(EnumType.STRING)
private Set<Color> colors;
...
}
...
public enum Color {
WHITE, RED, BLUE
}
Where colors is a Set of enums, and I want to make a search for all entities Airplanes that contains the color RED in this set. 颜色是一组枚举,我想搜索所有包含此集合中红色的实体。
Can I make that with Criterias or should I use HQL queries? 我可以使用“条件”来做到这一点还是应该使用HQL查询?
Thanks! 谢谢!
The criteria API is useful to create queries based on a dynamic set of... criteria. 条件API可用于基于一组动态...条件创建查询。 For a static query, HQL is always more readable:
对于静态查询,HQL始终更具可读性:
select a from Airplane a where :color member of a.colors
or 要么
select a from Airplane a join a.colors color where color = :color
should do the trick 应该可以
As suggested by JB Nizet, you can use HQL
to get the results: 正如JB Nizet所建议的那样,您可以使用
HQL
获得结果:
Query query = session.createQuery("from Airplane as airplane inner join "
+ "airplane.colors colors where colors =:color");
query.setParameter("color", Color.BLUE);
List<Airplane> list = query.list();
for (Airplane airplane : list) {
System.out.println("->" + airplane.getColors());
}
There is a way to perform such query using Criteria in Hibernate. 在Hibernate中有一种使用Criteria进行查询的方法。 You just have to join
colors
and ask for its elements
property (ie colors.elements
). 您只需要加入
colors
并要求其elements
属性(即colors.elements
)。
elements
is a keyword defined in Hibernate's CollectionPropertyNames
class and you can access your enum value using it. elements
是Hibernate的CollectionPropertyNames
类中定义的关键字,您可以使用它访问您的枚举值。
session.createCriteria(Airplane.class)
.createAlias("colors", "colors")
.add(Restrictions.eq("colors.elements", Color.BLUE))
.list()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.