Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping SQL View to JPA Entity

In my development project, I am using JPA (hibernate) as OR Mapping technology for database access. I sometimes hit performance issues and technical difficulties when I map DB table to entities directly for complex relationship.

I find a workaround is to map DB view to JPA entities. This make coding easier and sometimes performance is better. Do you think it is a anti-pattern of using JPA in this way?

like image 696
Boris Avatar asked Jul 04 '12 10:07

Boris


People also ask

How do I map a view with JPA?

In JPA you can map to a VIEW the same as a table, using the @Table annotation. You can then map each column in the view to your object's attributes. Views are normally read-only, so object's mapping to views are normally also read-only.

How do you indicate entity in JPA?

The JPA specification requires the @Entity annotation. It identifies a class as an entity class. You can use the name attribute of the @Entity annotation to define the name of the entity. It has to be unique for the persistence unit, and you use it to reference the entity in your JPQL queries.

Can we write SQL query in JPA?

We can create a SQL query with the @Query annotation by following these steps: Add a query method to our repository interface. Annotate the query method with the @Query annotation, and specify the invoked query by setting it as the value of the @Query annotation's value attribute.


1 Answers

This is not a workaround and not an anti-pattern. There is a topic on mapping JPA Entities to SQL Views. It gives you enough information whether to use this method or not.

Personally, I prefer Java classes, and thus I use Result Classes Constructor Expression. It instantiates and populates objects of provided class based on results query return.

You can view both of these methods which increases performance and reduces structure complexity.

like image 122
JMelnik Avatar answered Sep 30 '22 22:09

JMelnik