javajpaprimary-keycomposite-primary-keydatabase-view

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?


Solution

  • 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/