This one has me stumped. I have an idea how criteria works but for some reason this query is giving me issues not being able to find a property when it's clearly there.
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
Here's my criteria query:
Criteria criteria = session.createCriteria(Book.class)
.add(Restrictions.eq("shelf.shelfId", bookLocId))
.add(Restrictions.ne("shelf.shelfType", "table"))
.add(Restrictions.ne("bookState", "requested");
The problem is the middle restriction. It can't find shelfType
but it finds shelfId
just fine. Thank you for any help!
It finds shelfId
just fine, because it is the key of the association and therefore there is no join required for the query to see the ID. If you want to add restriction to other property, you must JOIN the shelf
association, for instance like this:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With