Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria could not resolve property when it's there

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!

like image 755
SS113 Avatar asked Jan 07 '23 06:01

SS113


1 Answers

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");
like image 56
Bohuslav Burghardt Avatar answered Jan 17 '23 13:01

Bohuslav Burghardt