Mapping a SQL View with no Primary Key to JPA Entity
Solution 1
One way to solve this is use a composite primary key by just adding the @Id annotation to the appropriate fields.
Solution 2
There is no best approach. As that is a View, you will never insert any data in it, meaning you can simply define a Primary Key over any of existing fields. Also you could try to mark that field with insertable=false, updatable=false
.
UPDATE
You know better your data, but in general in a view you cannot guarantee that all records are unique, which is why you should in general avoid working directly with entities from the view. I would suggest rather working with a Wrapper class, something like:
SELECT new com.domain.MyWrapper(field1, field2, field3, field4,...) FROM ViewEntity
Related videos on Youtube
user2144555
Updated on June 21, 2022Comments
-
user2144555 almost 2 years
In my Java App I want to get information that is stored in my Oracle Database, using JPA. In my Database I have a View, with a set of columns that I got from some other tables. I want to map that View. However, my View doesn't have a Primary Key, so I can't create a JPA Entity. I thought about use 2 columns as Foreign Keys.
What's the best way of implementing that? I've seen so many different approaches, that I can't decide which is the best for this case.
-
user2144555 over 10 yearsThat doesn't work when I get information about rows in the table in which the field set as Primary Key has equal content. No error is given, but the information comes changed.
-
V G over 10 yearsUpdated the response.
-
user2144555 over 10 yearsThanks, using a Composite Primary Key (with @IdClass annotation) solved my problem.
-
ViniciusPires about 9 yearsIf I had seen your answer some time ago, I'd never make a view on the Database and map it as an Entity. Uniqueness killed my app reports, and I almost gave up of my project because of that... Thank you
-
cabaji99 over 6 yearsThanks this is the solution, adding the @Id to the view solved my problem, i am using Arquillian so i had to add the entity for the view and add another field to add the primary key