简体   繁体   中英

JPA map view with no primary key to an entity

I've got a database view with no primary key. It has a set of columns which uniquely identify a row in the view, but three of those columns can be null . I've tried creating an entity with a composite primary key based on those four columns but when retrieving data from the view I get this error:

The primary key read from the row ... during the execution of the query was detected to be null.  Primary keys must not contain null.

Is there something I can do, for example, adding an automatically generated column when defining the view?

JPA Specification says that an Entity class must have a unique, immutable ID .

Logically, if it does not have any primary key, it can't be called entity. What you can do instead is create a POJO representation of your VIEW, then execute a SQL Native query, then map the result set to your POJO. Here's a sample using @SqlResultSetMapping / @ConstructorResult http://www.thoughts-on-java.org/result-set-mapping-constructor-result-mappings/

Not all entities have PKs that fit the definition of JPA. There are a couple of ways around it, all of them hacky.

1) modify the view to combine the fields (substituting nulls with sensible values) into one field, and map that as a PK

2) use the attribute converter functionality to substitute nulls with sensible values, then you can map the composite PK.

3) use RowID as a PK (this is ok only if you don't depend on the PK for anything long term, as RowIDs are not guranteed to stay consistent between runs.

I'm sure there are other similar workarounds, but I've used 1 and 2, and explored using 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM