如何使用java.util.List将@ManyToMany与主键映射到额外表中

时间:2016-06-20 21:07:52

标签: java hibernate jpa many-to-many

如果我这样做;

public class Address{

    @Id
    private String zipCode;

    @Id
    private String number;

    @Id
    @Column(columnDefinition = "varchar(255) default 'DONT HAVE'")
    private String complement;
    //get set
}

public class Client{

    @Id
    @Column(columnDefinition = "CHAR(11)")
    private String cpf;

    @ManyToMany(cascade = CascadeType.ALL)
    private Set<Address> addresses;
    //get set
}

...我有这个映射:

Image - Model using java.util.List with @ManyToMany

如果我这样做;

public class Address{

    @Id
    private String zipCode;

    @Id
    private String number;

    @Id
    @Column(columnDefinition = "varchar(255) default 'DONT HAVE'")
    private String complement;
    //get set
}

ssh localhost "printf \"%s %s %s\n\" a b \"last parameter\""

...我有这个映射:

Image - Model using java.util.Set with @ManyToMany

问题是: 如何获取@ManyToMany关系自动生成的额外表的属性是使用java.util.List的主外键(PFK)?

1 个答案:

答案 0 :(得分:0)

在我的jpa研究中,我们不需要在@ManyToMany生成额外表格中创建主键。

这是我的最终解决方案:

public class Client{

   @Id
   @Column(columnDefinition = "CHAR(11)")
   private String cpf;

   @ManyToMany(cascade = CascadeType.ALL)
   @JoinTable(name="client_address", joinColumns = {
     @JoinColumn(name = "client_cpf") },
     inverseJoinColumns = { @JoinColumn(name = "address_zipcode", 
       referencedColumnName="zipCode"), @JoinColumn(name = "address_number", 
         referencedColumnName="number", @JoinColumn(name = 
         "address_complement", 
         referencedColumnName="complement"},
     uniqueConstraints = @UniqueConstraint(columnNames = {
       "client_cpf", "address_zipcode", "address_number",  
       "address_complement" })
   private List<Address> addresses;
   //get set
}