当它存在时,Hibernate Criteria无法解析属性

时间:2015-11-01 16:32:38

标签: java hibernate hibernate-criteria

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

Shelf.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就好了。谢谢你的帮助!

1 个答案:

答案 0 :(得分:4)

它找到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");