如何在hbm.xml文件中的hibernate中创建复合主键

时间:2014-12-24 20:57:03

标签: java mysql hibernate orm composite-primary-key

我有以下三个简单的类。 如何在Rating.hbm.xml文件中映射Rating类,更具体地说是它的复合键? 我目前在hibernate文档(5.1.2.1。复合标识符)

中迷失了方向

每个评级可以有一本书和一个用户进行特定评级。 每个用户都可以进行很多评级。 每本书都有很多评分。

评级等级

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

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

用户类

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

预订课程

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

    public Book() {}
    ...
}

1 个答案:

答案 0 :(得分:1)

首先,您应该创建一个复合主键类,如下所示:

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>

并查看它是否适合您