gpt4 book ai didi

java - 一对多映射中的@ElementCollection @CollectionTable

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:52 25 4
gpt4 key购买 nike

我正在尝试使用嵌入式注释在 JPA 中建立关系,但我无法成功运行它,

这里我的数据库sql脚本如下,

create table TBL_COLLEGE(
id integer primary key generated always as identity (start with 1000, increment by 5),
name varchar(50)
)

create table TBL_COURSE(
Id integer primary key generated always as identity (start with 10, increment by 1),
college_Id integer references TBL_COLLEGE,
name varchar(50)
)

下面是 JPA 的代码,

@Embeddable
public class Course {
...
...
..
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name="ID")
private Integer courseId;

@Column(name="NAME")
private String courseName;

@Column(name="COLLEGE_ID")
private Integer collegeId;
....
// getter and setter
}

这是学院 map ,

@Entity
@Table(name="TBL_COLLEGE")
public class College implements Serializable{
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name="ID")
private Integer collegeId;

...
..
@ElementCollection(targetClass=Course.class,fetch= FetchType.LAZY)
@CollectionTable(name="TBL_COURSE",joinColumns=@JoinColumn(name="COLLEGE_ID"))
private Set<Course> course;
..
// getter and setter
}

但是如果我尝试坚持 College with Courses collection set,它给了我一个异常(exception),

ERROR: HCANN000002: An assertion failure occurred (this may indicate a bug in Hibernate)
org.hibernate.annotations.common.AssertionFailure: Declaring class is not found in the inheritance state hierarchy: com.entities.Course

....
..

能否请您告诉我我的方法是否错误,或者我对@CollectionTable 的理解仍然很少,我错了吗

最佳答案

因为你的两个表都有它们自己的 ID 列,Hibernate 会希望它们都是 @Entity 类型。 @Embeddables 没有自己的 ID。因此,第一步是将 Course 更改为 @Entity,以及相应的 @TableName 等。

这导致了第二个问题,即Course对象的集合不应该是一个@ElementCollection,它应该是一个@OneToMany。实体集合,使用 @JoinColumn 指定 COLLEGE_ID 将是来自 TBL_COURSE 的外键。

最后,在 College 中有一个 Course 的集合,在 Course 中有一个 College id , 你暗示你想要一个 bidirectional association .除其他影响外,您不应在 Course 中拥有学院的 ID。您应该只拥有 College 引用。如果您不需要从 Course->College 导航,您可能希望暂时删除它,直到您更好地理解 Hibernate 的对象映射。

关于java - 一对多映射中的@ElementCollection @CollectionTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15409048/

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