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

拟墨画扇 提交于 2019-12-25 04:27:15

问题


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? I'm currently getting quite lost in the hibernate documentation (5.1.2.1. Composite identifiers)

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() {}
    ...
}

回答1:


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:

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



来源:https://stackoverflow.com/questions/27642101/how-do-i-create-a-composite-primary-key-in-hibernate-within-the-hbm-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!