gpt4 book ai didi

java - Hibernate 不会在 getter 处获取 @Id 注释

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:51 26 4
gpt4 key购买 nike

问题

在我当前的项目中,我得到了这个AnnotationException:

org.hibernate.AnnotationException: No identifier specified for entity: my.package.EntityClass

有缺陷的代码

问题是由@Id注解引起的,我把它从field移到了getter:

@Entity
@Table(name = "MY_TABLE")
public class EntityClass extends BaseEntityClass {

private long id;

@Override
public void setId(long id) {
this.id = id;
}

@Override
@Id
@SequenceGenerator(name = "FOOBAR_GENERATOR", sequenceName = "SEQ_MY_TABLE", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FOOBAR_GENERATOR")
public long getId() {
return this.id;
}

}

工作代码

当我改为注释 id 属性时,它工作正常:

@Entity
@Table(name = "MY_TABLE")
public class EntityClass extends BaseEntityClass {

@Id
@SequenceGenerator(name = "FOOBAR_GENERATOR", sequenceName = "SEQ_MY_TABLE", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FOOBAR_GENERATOR")
private long id;

@Override
public void setId(long id) {
this.id = id;
}

@Override
public long getId() {
return this.id;
}

}

文档引用

Hibernate documentation状态:

By default the access type of a class hierarchy is defined by the position of the @Id or @EmbeddedId annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If there annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter. That works well in practice and is the recommended approach.

问题

我的类有额外的属性,我想在其中注释 getter。所以我还需要在 getter 处添加 @Id 注释。

这在之前的其他项目中运行良好,但这次 Hibernate 似乎没有在 getter 被注释时获取实体的标识符。

  • 我是否需要更改任何其他配置属性?

  • 或者这种行为是否在 Hibernate 版本之间发生了变化?

最佳答案

您需要始终对所有 getter 使用 @Id。确保没有使用 @Id 而不是 getters 注释的字段。混合和匹配会阻止它正常工作。

关于java - Hibernate 不会在 getter 处获取 @Id 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com