Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Hibernate Tips: How to Map a View With Hibernate

DZone's Guide to

Hibernate Tips: How to Map a View With Hibernate

Using Hibernate and need to map read-only database views? Here's a quick, simple solution to your problem using the @Immutable annotation.

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. Some of the most popular tips are also available as a book.

If you have a question for a future Hibernate Tip, please leave a comment below.

Get more videos in the Hibernate Tips playlist

Question:

How can I map a read-only database view with Hibernate?

Solution:

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.

@Entity
@Immutable
public class BookView {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

  @Version
    private int version;

    private String title;

    @Temporal(TemporalType.DATE)
    private Date publishingDate;

    private String authors;

    ...

}


The @Immutable annotation tells Hibernate to ignore all changes on this entity, but you can use it in your queries to read data from your database.

List<BookView> bvs = em.createQuery("SELECT v FROM BookView v", BookView.class).getResultList();


If you like this post, check out my book Hibernate Tips: More than 70 solutions to common Hibernate problems.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
hibernate ,jpa ,java ,mapping views ,read-only ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}