【问题标题】:How do I query for objects with a value in a String collection using Hibernate Criteria?如何使用 Hibernate Criteria 在 String 集合中查询具有值的对象?
【发布时间】:2011-01-20 05:49:59
【问题描述】:

假设 Student 是包含 ComputerScienceStudent 和 ITStudent 的继承层次结构中的父类。 Student 定义了一个名为 favoriteColors 的字段,它是一个值类型的字符串集合。使用条件 API,我想查询所有将“蓝色”列为他们最喜欢的颜色之一的学生。

这里是相关的java sn -p

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
abstract class 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 是继承层次结构中的抽象父类,我无法创建具体的 Student 作为示例传递。

这可能吗?感谢您的宝贵时间!

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    你试过写吗

    List students = sess.createCriteria(Student.class)
    .add(Restrictions.eq("favoriteColors", "blue") )
    .list();
    

    编辑:好的,这不起作用。根据this related question,目前无法使用 Criteria API 引用值类型集合的元素。

    【讨论】:

    • 刚刚做了,失败并显示消息 ERROR org.hibernate.util.JDBCExceptionReporter - Parameter #1 is not set
    • 我明白了。编辑包括在内 - 我发现了一个相关的问题,希望能有所帮助。
    • 那是个坏消息。不过谢谢。至少现在我知道在 hibernate 获得这个功能之前不要继续走这条路。
    猜你喜欢
    • 1970-01-01
    • 2010-09-10
    • 2012-01-29
    • 2010-12-30
    • 2019-01-30
    • 2010-12-18
    • 2015-03-03
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多