【问题标题】:Hibernate Criteria could not resolve property when it's there当属性存在时,休眠标准无法解析属性
【发布时间】:2016-02-01 13:24:53
【问题描述】:

这个让我难过。我知道标准是如何工作的,但由于某种原因,这个查询给了我一个问题,当它明显存在时无法找到它。

货架.java

@Entity
@Table(name="BOOKSHELF")
public class Shelf {

@Id
private int shelfId;
private String shelfName;
private String shelfType;
@OneToMany(mappedBy="shelf",cascade=CascadeType.ALL)
private Set<Book> book = new HashSet<Book>(0);

//getters&setters here

Book.java

@Entity
@Table(name="BOOKS")
public class Book {

@Id
private int bookId;
private String bookName;
private String bookState;
@ManyToOne(cascade=CascadeType.ALL)
private Shelf shelf;    

//getters&setters here

这是我的条件查询:

Criteria criteria = session.createCriteria(Book.class)
                    .add(Restrictions.eq("shelf.shelfId", bookLocId))
                    .add(Restrictions.ne("shelf.shelfType", "table"))
                    .add(Restrictions.ne("bookState", "requested");

问题是中间限制。它找不到shelfType,但它找到shelfId 就好了。感谢您的帮助!

【问题讨论】:

    标签: java hibernate hibernate-criteria


    【解决方案1】:

    它找到shelfId 就好了,因为它是关联的键,因此查询不需要连接即可查看ID。如果要对其他属性添加限制,则必须加入shelf 关联,例如:

    Criteria criteria = session.createCriteria(Book.class)
             // JOINs shelf association and creates alias 'shelf' for it
             .createAlias("shelf", "shelf")
             .add(Restrictions.eq("shelf.shelfId", bookLocId))
             .add(Restrictions.ne("shelf.shelfType", "table"))
             .add(Restrictions.ne("bookState", "requested");
    

    【讨论】:

    • 谢谢博胡斯拉夫!那效果很好。我确实查看了.createAlias,但也许我第一次没有正确使用它。再次感谢。现在更清楚了。
    猜你喜欢
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多