Java @ElementCollection@CollectionTable在一对多映射中
我正在使用嵌入式注释尝试JPA中的关系,但我无法成功运行它 这里我的数据库sql脚本如下:Java @ElementCollection@CollectionTable在一对多映射中,java,hibernate,jpa,jpa-2.0,Java,Hibernate,Jpa,Jpa 2.0,我正在使用嵌入式注释尝试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 alw
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)
)
create table TBL_COURSE(
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
}
这是大学地图
@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
}
你能告诉我我的方法是不是错了,
或者我对@CollectionTable的理解仍然很肤浅,
如果我出错了您必须定义两个pojo的连接
@OneToMany
@JoinColumn(name=course table column id)
private Set<Course> course;
@OneToMany
@JoinColumn(名称=课程表列id)
私人课程;
因为两个表都有自己的ID
列,所以Hibernate希望它们都是@Entity
类型@embeddedables
没有自己的ID
。因此,第一步是将过程
更改为@实体
,并使用相应的@TableName
等
这导致了第二个问题,即课程
对象的集合不应该是@ElementCollection
,它应该是一个实体集合,带有@JoinColumn
指定学院ID
将是TBL\课程
的外键
最后,通过在
学院
中收集课程
,以及在课程
中拥有学院
id,您就意味着您想要一个。除此之外,你不应该在课程
中拥有学院的ID
。您只需拥有学院
参考资料即可。如果您不需要从课程
->学院
,您可能现在就想删除它,直到您更好地理解Hibernate的对象映射。虽然我的方法不合适,但它仍然在代码中进行了一些小的更改
首先,我放弃了表TBL_课程,创建了一个新的表,如下所示
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)
)
create table TBL_COURSE(
college_Id integer references TBL_COLLEGE,
name varchar(50)
)
在这里你可以看到我已经删除了主键,现在只有引用键和名称
现在在Course.java中,我做了如下工作:
@Embeddable
public class Course {
// constuctor
@Column(name="NAME")
private String courseName;
..
// setter getter
}
这里我删除了@Id注释和Id属性,甚至删除了College_Id映射
其余代码与College.java中的代码相同
它成功了
等待意见没关系,只要你想
课程
的生命周期由学院定义,而不是一个独立的实体。您也将无法子类化课程
等。不需要定义一个文档注释等。。从嵌入类中删除ID注释就足够了。当然,GeneratedValue注释也应该被删除。@asch-如果您假定OP不希望课程成为一流对象,那么这是真的。但是,如果表是定义的,删除ID注释会导致问题。Courses已经被注释为可嵌入的,因此它无论如何都不是实体(我猜您的意思是“第一类对象”)