Java 如何在没有@Id的情况下使用spring Repository?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29561885/
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 use spring Repository without @Id?
提问by membersound
I'm using spring CrudRepository
throughout my application.
Now I want to also create one for an @Entity
that does not have an @Id
. Is that possible at all?
我在CrudRepository
整个应用程序中都使用 spring 。现在我还想为@Entity
没有@Id
. 这可能吗?
//probably ID is always required?
public interface Repository<T, ID extends Serializable>
采纳答案by Sergey Pauk
JPA requires that every entity has an ID. So no, entity w/o an ID is not allowed.
JPA 要求每个实体都有一个 ID。所以不,不允许没有 ID 的实体。
Every JPA entity must have a primary key.
每个 JPA 实体都必须有一个主键。
from JPA spec
来自JPA 规范
You may want to read more about how JPA handles a case when there's no id on the DB side from here (see 'No Primary Key').
您可能想从此处阅读更多有关 JPA 如何处理 DB 端没有 id 的情况的信息(请参阅“无主键”)。
回答by sourabhteke
Alternatively you can extend AbstractPersistable<Long>
for your all POJO entities.
或者,您可以扩展AbstractPersistable<Long>
所有 POJO 实体。
Follow example: - https://github.com/spring-projects/spring-data-examples/blob/master/jpa/example/src/main/java/example/springdata/jpa/simple/User.java