如何使用Hibernate Criteria查询具有String集合中值的对象? [英] How do I query for objects with a value in a String collection using Hibernate Criteria?
问题描述
以下是相关的java片段
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
抽象类Student {
@CollectionOfElements
Set< String> favoriteColors = new TreeSet< String>();
我查看了 http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html 看起来像这样的东西可能是一个开始
List students = sess.createCriteria(Student.class)
.createCriteria(favoriteColors)
.add(Restrictions.eq(??????,blue))
.list();
但是我不知道要填写什么属性名称,因为String不是我定义的类(因此??????)
我真的想避免使用HQL,除非绝对没有办法使用标准来做到这一点。我也想避免添加sqlRestrictions。我不认为示例API会起作用,因为Student是继承层次结构中的抽象父类,并且我无法创建具体的学生作为示例传入。
<这可能吗?感谢您的时间!
您是否尝试过写作
<$ p $ (学生类)
.add(Restrictions.eq(favoriteColors,blue))
.list();
编辑:好的,那不行。根据这个相关的问题,引用使用Criteria API,价值型集合的元素目前是不可能的。
Let's say Student is the parent class in an inheritance hierarchy that includes ComputerScienceStudent and ITStudent. Student defines a field called favoriteColors, which is a value-typed collection of Strings. Using the criteria API I'd like to query for all students who list "blue" as one of their favoriteColors.
Here is the relevant java snippet
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
abstract class Student {
@CollectionOfElements
Set<String> favoriteColors = new TreeSet<String>();
I looked at the hibernate documentation found at http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html and it looks like something like this might be a start
List students = sess.createCriteria(Student.class)
.createCriteria("favoriteColors")
.add( Restrictions.eq(??????, "blue") )
.list();
but I don't know what to fill in as the name of the property since String is not a class I defined (thus the ??????)
I'd really like to avoid using HQL unless there is absolutely no way to do this using criteria. I'd also like to avoid adding sqlRestrictions. I don't think the example API will work because Student is the abstract parent class in an inheritance hierarchy and I can't create a concrete Student to pass in as an example.
Is this possible? Thanks for your time!
Have you tried writing
List students = sess.createCriteria(Student.class)
.add(Restrictions.eq("favoriteColors", "blue") )
.list();
Edit: Ok, that doesn't work. According to this related question, refering to elements of value-type collections is currently impossible using the Criteria API.
这篇关于如何使用Hibernate Criteria查询具有String集合中值的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!