简体   繁体   English

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

[英]How do I create a composite primary key in hibernate within the hbm.xml file

I have the following three simple classes. 我有以下三个简单的类。 How do I go about mapping the Rating class and more specifically its composite key in my Rating.hbm.xml file? 如何在我的Rating.hbm.xml文件中映射Rating类,尤其是其组合键? I'm currently getting quite lost in the hibernate documentation (5.1.2.1. Composite identifiers) 我目前在休眠文档(5.1.2.1。复合标识符)中迷路了

Each rating can have one book and one user making that specific rating. 每个评分可以有一本书,一个用户可以进行特定评分。 Each user can make many ratings. 每个用户可以进行许多评级。 Each book can have many ratings. 每本书可以有很多等级。

Classes 班级

Rating class 等级等级

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

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

User class 用户类别

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

Book class 书本类

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

    public Book() {}
    ...
}

Firstly you should create a composite primary key class like this: 首先,您应该创建一个这样的复合主键类:

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 */ 


}

Now create your main Rating class like this: 现在,像这样创建您的主要Rating类:

public class RatingBook {
RatingId RatingId;
private Date timestamp;

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

}

You may try the following: 您可以尝试以下方法:

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

and see if that works for you 看看是否适合您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM