java 使用JPA时如何映射没有主键的数据库视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31292050/
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
How to map a database view without a primary key when using JPA
提问by Andy N
- I have views in a SQL database with no obvious primary key (composite or otherwise)
- I would like to access them through JPA
- 我在没有明显主键(复合或其他)的 SQL 数据库中有视图
- 我想通过 JPA 访问它们
I've read that I should be able to treat views in JPA like I treat tables (using the @Table annotation etc.). However without a primary key I have to effectively make a composite key out of EVERY COLUMN (in fact, this in what Hibernate's reverse-engineering tool seems to do by default).
我读过我应该能够像对待表格一样对待 JPA 中的视图(使用 @Table 注释等)。但是,如果没有主键,我必须有效地从每个列中创建一个复合键(实际上,这在 Hibernate 的逆向工程工具中似乎默认是这样做的)。
However if I do this there are undesirable side effects. E.g.
但是,如果我这样做会产生不良副作用。例如
Having to write all you code pointing to the primary key's attributes rather than the views:
myViewObject.getPrimaryKey().getFirstName()
Not being able to use the "findBy..." methods on the spring Repository (since that attribute is part of the view's "identifier" and not actually one of it's attributes).
必须编写指向主键属性而不是视图的所有代码:
myViewObject.getPrimaryKey().getFirstName()
无法在 spring 存储库上使用“findBy...”方法(因为该属性是视图“标识符”的一部分,实际上并不是它的属性之一)。
My question is: How do I map views in such a was as I can easily access their attributes using JPA?
我的问题是:如何在这样的情况下映射视图,因为我可以使用 JPA 轻松访问它们的属性?
Note: I'm quite happy to be told I'm using completely the wrong approach. This seems like such a common problem there's bound to be a better solution.
注意:我很高兴被告知我使用了完全错误的方法。这似乎是一个普遍存在的问题,肯定会有更好的解决方案。
回答by Vlad Mihalcea
You can add a UUID column to every row of the Views so then you can use the UUID column as an @Id.
您可以向视图的每一行添加一个 UUID 列,这样您就可以将 UUID 列用作 @Id。