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?
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.
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
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
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!