James
James

Reputation: 223

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

Upvotes: 1

Views: 3301

Answers (1)

nathandrake
nathandrake

Reputation: 427

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

Upvotes: 1

Related Questions