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

Categories

0 votes
1.1k views
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

post_table

Comment 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).

activity_table

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:

@Entity
@IdClass(ActivityKey.class)
class Activity {
    @Id
    private Integer activity_id;
    @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
...