Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

java - How to use primary key of multiple tables as primary key of third table in hibernate

I have two tables as following

Post table


Comment table


Now i want to create another table called Activity table which will store aggregate values of likes performed on post or comment. So i want to use activity id field which must be EITHER post id or comment id and type field which could be post/comment (string).


I want to make composite primary key of both this fields. How should i do this in Hibernate?

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make use of @IdClass to make a composite key with those two fields. First, you need to define a new class that will hold the composite key fields:

public class ActivityKey implements Serializable {
    protected Integer activity_id;
    protected String type;

    public ActivityKey () {}

    public ActivityKey (Integer activity_id, String type) {
        this.activity_id= activity_id;
        this.type= type;

And then, your Activity class must look like this:

class Activity {
    private Integer activity_id;
    private String type;

    //Other fields

There are restrictions to apply when defining the primary key class (ActivityKey in this example). This class must be serializable and must define both hashCode() and equals() methods. Also, it must be public and have a public no-arg constructor.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share