java 如何设置没有@id 元素的@entity?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30712842/
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 set a @entity without @id element?
提问by Alfredo M
I have this bean:
我有这个豆子:
@Entity
@Table(name = "accesos")
public class Acceso implements Serializable {
/** */
@Column(name = "idUser")
private String idUser;
/** */
@ManyToOne
@JoinColumn(name = "idArea")
private Area area;
/** */
@ManyToOne
@JoinColumn(name = "idRol")
private Rol rol;
But I get this error:
但我收到此错误:
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com...Acceso
引起:org.hibernate.AnnotationException:没有为实体指定标识符:com...Acceso
How can I set this bean? What I need is based on the user ID get all the ROL-AREA that he has access.
我怎样才能设置这个bean?我需要的是根据用户 ID 获取他有权访问的所有 ROL-AREA。
I tried change the @Entity
to @Embedded
, but when I make the search no result is returned, and even in the log is no SQL sentence executed.
我尝试将 更改@Entity
为@Embedded
,但是当我进行搜索时,没有返回任何结果,甚至在日志中也没有执行 SQL 语句。
回答by slartidan
You have to have an identity for each bean, there is no way around. You can however use a combined key, if none of your fields is unique.
您必须为每个 bean 指定一个身份,这是没有办法的。但是,如果您的所有字段都不是唯一的,您可以使用组合键。
If the combination of all your fields is unique, then try to annotate all fieldswith @Id
. Take as few fields as possible, but as many as required to make the combination unique.
如果您的所有字段的组合是唯一的,然后尝试注释的所有字段与@Id
。使用尽可能少的字段,但需要尽可能多的字段以使组合独一无二。
回答by EmirCalabuch
JPA Specifications state that all Entities must have an identifier (JSR 317, section 2.4). It can be a single column or a composite key.
JPA 规范声明所有实体都必须有一个标识符(JSR 317,第 2.4 节)。它可以是单列或组合键。
You can either put an idAcceso
identifier in the Acceso
entity or not make Acceso
an entity but rather a "component" (which is the purpose of the @Embeddable
annotation). Components do not require an ID but cannot be queried separately (i.e. you cannot do select a from Acceso a
but rather you need to query for User
and then use the accessor method user.getAccesos()
.
您可以idAcceso
在Acceso
实体中放置标识符,也可以不创建Acceso
实体而是创建“组件”(这是@Embeddable
注释的目的)。组件不需要 ID 但不能单独查询(即您不能这样做select a from Acceso a
,而是需要查询User
然后使用访问器方法user.getAccesos()
.
You cannot substitute @Entity
with @Embedded
in this context.
在这种情况下,您不能用@Entity
with代替@Embedded
。
@Embeddable
public class Acceso {
// ...
}
@Entity
public class User {
@Id protected String id;
// ...
@ElementCollection
@CollectionTable(
name="USER_ACCESSES",
joinColumns=@JoinColumn(name="USER_ID")
protected Set<Acceso> accesos = new HashSet<Acceso>();
}
回答by slarge
You don't have an id specified and you MUST so add @Id annotation onto idUser
您没有指定 id,因此必须在 idUser 上添加 @Id 注释
@Id
@Column(name = "idUser")
private String idUser;