2013-03-14 152 views
7

我使用嵌入式註解在JPA努力之間的關係,但我不能夠成功運行,@ElementCollection @CollectionTable在一對多映射

這裏我的數據庫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 
} 

這裏是學院的映射,

@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",[email protected](name="COLLEGE_ID")) 
    private Set<Course> course; 
    .. 
    // getter and setter 
} 

但如果我嘗試堅持與大學課程收集組, 它給了我一個例外,

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理解仍然微乎其微, 是我錯了

回答

5

因爲你的表都有自己的ID列,Hibernate會希望它們都是@Entity類型。 @Embeddables沒有自己的ID。所以,第一步是要改變Course@Entity,相應@TableName

這導致了第二個問題,這是Course對象的集合不應該是一個@ElementCollection,它應該是一個@OneToMany實體收集,@JoinColumn指定COLLEGE_ID將是來自TBL_COURSE的外鍵。

最後,通過在CourseCourseCollege集合,以及一個College ID,你是暗示你想要一個bidirectional association。除此之外,您不應該在Course中擁有大學的ID。你應該只有College參考。如果您不需要從Course - >College導航,那麼您現在可能需要刪除它,直到您對Hibernate的對象映射有了更好的理解。

+0

沒有必要定義一對多註釋等。這足以從embedde刪除ID註釋d類。當然,GeneratedValue註解也應該被移除。 – asch 2016-12-19 14:19:36

+0

@asch - 如果您認爲OP不希望課程成爲頭等對象,那麼這是真的。根據定義的表格,刪除ID註釋會導致問題。 – sharakan 2017-01-03 04:44:24

+0

課程已經註解爲Embeddable,所以它不是實體(我想你的意思是「第一類對象」) – asch 2017-01-03 06:52:58

0

你必須定義加入約兩POJO

@OneToMany 
@JoinColumn(name=course table column id) 
private Set<Course> course; 
0

雖然我的做法是不正確的,但它仍然在代碼中的一些小的改動工作,

首先我刪除的表TBL_COURSE,創造一個新的,如下,

create table TBL_COURSE( 
    college_Id integer references TBL_COLLEGE, 
    name varchar(50) 
) 

在這裏你可以看到我已經刪除了主鍵,現在只有參考鍵和名字,

Now in Course。java中,我沒有以下,

@Embeddable 
public class Course { 

// constuctor 

@Column(name="NAME") 
private String courseName; 
.. 
// setter getter 
} 

在這裏,我已刪除@Id註釋和id屬性,我已甚至除去College_Id映射,

和代碼的其餘部分是相同的存在於College.java ,

和它的工作,

等待意見

+0

沒問題,只要你想讓'Course'讓它的生命週期由'College'定義,而不是一個獨立的實體。你也不能將'課程'等子類化。 – sharakan 2013-03-14 13:42:29