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.
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").
Is it at all possible to add a view to the Entity model without a unique identifier? If without a primary key, no.
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.
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.
One way to solve this is use a composite primary key by just adding the @Id annotation to the appropriate fields.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With