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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:13:04  来源:igfitidea点击:

How to use spring Repository without @Id?

javaspringjpaspring-data

提问by membersound

I'm using spring CrudRepositorythroughout my application. Now I want to also create one for an @Entitythat 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

按照示例: - https://github.com/spring-projects/spring-data-examples/blob/master/jpa/example/src/main/java/example/springdata/jpa/simple/User.java