简体   繁体   English

没有实体主键的JPA映射视图

[英]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 . 它具有一组在视图中唯一标识行的列,但是其中三列可以为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 . JPA规范指出, Entity类必须具有唯一的,不变的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. 相反,您可以做的是创建VIEW的POJO表示形式,然后执行SQL Native查询,然后将结果集映射到POJO。 Here's a sample using @SqlResultSetMapping / @ConstructorResult http://www.thoughts-on-java.org/result-set-mapping-constructor-result-mappings/ 下面是一个使用样本@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. 并非所有实体都有符合JPA定义的PK。 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 1)修改视图以将字段(将空值替换为有意义的值)组合为一个字段,并将其映射为PK

2) use the attribute converter functionality to substitute nulls with sensible values, then you can map the composite PK. 2)使用属性转换器功能用合理的值替换空值,然后可以映射复合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. 3)将RowID用作PK(只有在长期不依赖PK的情况下才可以,因为不保证RowID在两次运行之间保持一致。

I'm sure there are other similar workarounds, but I've used 1 and 2, and explored using 3. 我敢肯定还有其他类似的解决方法,但是我使用了1和2,并使用了3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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