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.
How can I map a read-only database view with Hibernate?
Don’t want to read? You can watch it here!
Database views, in general, are mapped in the same way as database tables. You just have to define an entity that maps the view with the specific name and one or more of its columns.
But the normal table mapping is not read-only, and you can use the entity to change its content.
Depending on the database you use and the definition of the view, you’re not allowed to perform an update on the view content. You should therefore also prevent Hibernate from updating it.
You can easily achieve this with the Hibernate-specific @Immutable annotation which I use in the following code snippet.
The @Immutable annotation tells Hibernate to ignore all changes on this entity, but you can use it to retrieve data from the database.
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.
Views can be a nice way to pre-process the existing data in the database to improve the performance of your application. You can learn more about performance optimizations in my Hibernate Performance Tuning Online Training.
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.