Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
I want to exclude some records from an association mapping. How can I filter the elements of a mapped entity association?
You can use Hibernate’s @Where annotation to define an SQL clause which filters the elements of a mapped association.
Let’s take a look at an example. Books can be published in different formats, e.g. as an ebook or as a paperback. You can model that with a Book entity and a Format enum.
Each Book was written by one or more authors. So, you need a many-to-many association between the Book and the Author entity. As you can see in the code snippet, I modeled that as a typical many-to-many association on the Book entity.
You could, of course, do the same on the Author entity. But let’s say you want to use different associations for ebooks and physical books. In that case, you need to define 2 associations on the Author entity and filter them accordingly.
As you can see in the following code snippet, you can easily do that with a @Where annotation. You just need to provide an SQL expression which Hibernate adds to the WHERE clause of the SQL statement.
When you now load an Author entity and initialize the associations, Hibernate executes independent SQL statements to get the elements of the ebooks and printBooks association and uses the provided SQL snippet in the WHERE clause.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
Another common use case for Hibernate’s @Where annotation is the implementation of a soft delete. I explain that in more detail in How to implement a soft delete with Hibernate.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.