Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a SQL View with no Primary Key to JPA Entity

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.

like image 644
user2144555 Avatar asked Nov 25 '13 20:11

user2144555


People also ask

Does JPA require primary key?

Every JPA entity must have a primary key. You can specify a primary key as a single primitive, or JDK object type entity field (see "Configuring a JPA Entity Simple Primary Key Field").

Can we create a view without primary key?

Is it at all possible to add a view to the Entity model without a unique identifier? If without a primary key, no.

How do I map a view in 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.

Can we define entity class without primary key?

When you define an entity object, it must have a primary key or use a RowID attribute (based on the table's ROWID). To do so, you must create a new attribute while you are defining your entity object in the Entity Object Wizard.


2 Answers

One way to solve this is use a composite primary key by just adding the @Id annotation to the appropriate fields.

like image 175
PepperBob Avatar answered Sep 17 '22 08:09

PepperBob


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
like image 33
V G Avatar answered Sep 18 '22 08:09

V G