2014-12-24 70 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