how to make a composite primary key (java persistence annotation)

前端 未结 5 1063
天命终不由人
天命终不由人 2020-11-29 06:05

How to make it so that the table user_roles defines the two columns (userID, roleID) as a composite primary key. should be easy, just can\'t remember/find.

In

5条回答
  •  生来不讨喜
    2020-11-29 06:32

    I had the same Problem with the primary keys. I also knew the solution with the @Embeddable and @EmbeddedId Class. But i wanted just the simple solution with the annotations.

    Well i found enlightenment through this article: http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html

    and here is the magic:

    this generates a primary key on the join table:

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="classA_classB")
    private Set classesA;
    

    this dosn't generate a primary key on the join table:

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="classA_classB")
    private List classesA;
    

    at least in my enviroment

    Note that the difference is using Set or List

提交回复
热议问题