I'm trying to build a Hibernate Criteria query to find entities that have a specific element inside a collection.
We can take as an example a Book -object that looks like this:
public class Book {
private Long id;
private String title;
private Set<String> authors = new HashSet<String>();
}
The entity is mapped like this:
<class name="Book" table="Book">
<id name="id" column="BOOK_ID">
<generator class="native"/>
</id>
<property name="title"/>
<set name="authors" table="Book_Authors">
<key column="BOOK_ID"/>
<element type="string" column="AUTHORS"/>
</set>
</class>
Now I would like to find out which books are written by Matt. With pure SQL I can do a query like this:
String author = "Matt";
String query = "SELECT * FROM Book " +
"WHERE BOOK_ID IN " +
"(SELECT BOOK_ID FROM Book_Authors " +
"WHERE authors = :author )";
List<Book> result = session.createSQLQuery(query)
.addEntity(Book.class)
.setParameter("author", author)
.list();
This works all good and well, and I get out all books that Matt has been a part of writing. The project I work in, however, uses the Criteria API instead of raw SQL, and I haven't found a way to express the same query in that form. I've taken a look on the Restrictions API and the closest I've found is Restions.in(propertyName, collection) but that works the other way around (one value in object, many values to match against).
Any ideas?
Let’s say the following is our array of objects − To get only specific values in an array of objects in JavaScript, use the concept of filter (). node fileName.js.
Find Object In Array With Certain Property Value In JavaScript - Andreas Wik If you have an array of objects and want to extract a single object with a certain property value, e.g. id should be 12811, then find() has got you covered. HOME Find Object In Array With Certain Property Value In JavaScript July 7, 2020 by Andreas Wik
criteriaQuery.select (root) .where (root.get ( "title" ) .in (titles)); In a contrast to the CriteriaBuilder.in (), the Expression.in () accepts a collection of values. As we can see it also simplifies our code a little bit. 5. IN Expressions Using Subqueries So far, we have used collections with predefined values.
The existing elements will be copied to the new array before the addition of the new element. match: It is the Predicate<T> delegate that defines the conditions of the elements which is to be searched.
Have you tried using HQL?
SELECT bk FROM Book bk WHERE :author IN bk.authors
HQL is generally more powerful than Criteria, so you may be stuck with it.
Simplest way would be to use an sql restriction, for now:
criteria.add(Restrictions.sqlRestriction("BOOK_ID IN " +
"(SELECT BOOK_ID FROM Book_Authors " +
"WHERE authors = " + author + " )"));
Or you could write your own criterion.
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