How to create join table with JPA annotations?

后端 未结 4 1302
深忆病人
深忆病人 2020-12-04 10:12

I need to create a join table in my database using JPA annotations so the result will be this:

\"ent

4条回答
  •  旧时难觅i
    2020-12-04 11:11

    You definitely shouldn't create User_Group entity as it's more the underlying database representation than the object oriented one.

    You can achieve the join table by defining something like:

    @Entity
    @Table(name="USERS", schema="ADMIN")
    public class User implements Serializable {
    //...
    
    @ManyToOne
    @JoinTable(name="USER_GROUP")
    Group group;
    

    @Entity
    @Table(name="GROUPS", schema="ADMIN")
    public class Group implements Serializable {
    //...
    
    @OneToMany(mappedBy="group")
    Set users;
    

    Edit: If you want to explicitly set the names of the columns you could use @JoinColumn elements as shown below:

    @ManyToOne
    @JoinTable(name="USER_GROUP",
        joinColumns = @JoinColumn(name = "userid", 
                                  referencedColumnName = "userid"), 
        inverseJoinColumns = @JoinColumn(name = "groupid", 
                                  referencedColumnName = "groupid"))
    Group group;
    

提交回复
热议问题