2014-12-24 97 views
0

我有以下三個簡單的類。 我該如何着手在Rating.hbm.xml文件中映射Rating類和更具體的組合鍵? 我目前在hibernate文檔中相當迷茫(5.1.2.1。複合標識符)如何在hbm.xml文件中的hibernate中創建複合主鍵

每個評分可以有一本書和一個用戶進行特定評分。 每個用戶可以做很多評級。 每本書都可以有很多評分。

評級類

public class Rating { 
     private User user; 
     private Book book; 
     private int rating; 
     private Date timestamp; 

     public Rating() {} //No arg contructor for hibernate 
    ... 
} 

User類

public class User { 
    private long userId; 
    private String email, password; 
    public User() {} 
    ... 
} 

Book類

public class Book { 
    private long bookId; 
    private String title; 

    public Book() {} 
    ... 
} 

回答

0

首先應該創建像複合主鍵類這樣的:

public class RatingId implements Serializable{ 
private User user; 
private Book book; 
private int rating; 
// an easy initializing constructor 
public PurchasedTestId(User user, Book book, int rating){ 
this.user = user; 
this.book = book; 
this.rating= rating; 
} 

/*create your getter and setters plus override the equals and hashCode() methods */ 


} 

現在創建您的主要評級類是這樣的:

public class RatingBook { 
RatingId RatingId; 
private Date timestamp; 

/* generate getters and setters for these two methods*/ 

} 

你可以嘗試以下方法:

<composite-id name=」ratingId」> 
<key-property name="user" column="user" /> 
<key-property name="book" column="book" /> 
<key-property name="rating" column="pid" /> 
</composite-id> 

,看看是否適合你

+0

謝謝,我現在就試試。評級是否在RatingId類別上,而不在RatingBook類別中是否有任何理由? – James