Java 将没有主键的 SQL 视图映射到 JPA 实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20202413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping a SQL View with no Primary Key to JPA Entity
提问by user2144555
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.
在我的 Java 应用程序中,我想使用 JPA 获取存储在我的 Oracle 数据库中的信息。在我的数据库中,我有一个视图,其中包含从其他一些表中获取的一组列。我想映射那个视图。但是,我的View 没有 Primary Key,因此我无法创建 JPA 实体。我想过使用 2 列作为外键。
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.
实现它的最佳方法是什么?我见过很多不同的方法,我无法决定哪种方法最适合这种情况。
采纳答案by PepperBob
One way to solve this is use a composite primary key by just adding the @Id annotation to the appropriate fields.
解决此问题的一种方法是通过将 @Id 注释添加到适当的字段来使用复合主键。
回答by Andrei I
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
.
没有最好的方法。由于这是一个视图,您永远不会在其中插入任何数据,这意味着您可以简单地在任何现有字段上定义主键。您也可以尝试用insertable=false, updatable=false
.
UPDATE
更新
You know better your data, but in generalin a view you cannot guarantee that all records are unique, which is why you should in generalavoid working directly with entities from the view. I would suggest rather working with a Wrapper class, something like:
您更了解您的数据,但通常在视图中您不能保证所有记录都是唯一的,这就是为什么您通常应该避免直接使用视图中的实体。我建议宁可使用 Wrapper 类,例如:
SELECT new com.domain.MyWrapper(field1, field2, field3, field4,...) FROM ViewEntity