[英]How do I fix my hibernate hbm.xml file to make my composite primary keys work? (MappingException)
[英]How do I create a composite primary key in hibernate within the hbm.xml file
我有以下三個簡單的類。 如何在我的Rating.hbm.xml文件中映射Rating類,尤其是其組合鍵? 我目前在休眠文檔(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() {}
...
}
首先,您應該創建一個這樣的復合主鍵類:
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 */
}
現在,像這樣創建您的主要Rating類:
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>
看看是否適合您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.