jpa一对多复合主键映射

时间:2017-04-28 14:07:35

标签: java hibernate jpa one-to-many composite-key

我有两张表如下:

TABLE_A
-------
A_SIREN
A_NDA

TABLE_B
-------
B_id    
B_NDA
B_SIREN

表A的ID是COMPOSITE KEY SIREN / NDA

这是实体代码。

关键班

@Embeddable
public class SirenNdaKey implements Serializable {
  @Column(name = "A_SIREN")        
  protected String siren;
  @Column(name = "A_NDA")        
  protected String nda;
  // getters setters
}

表A

public class EntityA{

   @EmbeddedId  
   private SirenNdaKey sirenNda;

   @OneToMany(fetch = FetchType.LAZY)
      @PrimaryKeyJoinColumns({ @PrimaryKeyJoinColumn(name = "A_SIREN", 
    referencedColumnName = "B_SIREN"),
      @PrimaryKeyJoinColumn(name = "A_NDA", referencedColumnName = "B_NDA") 
    })
   private Set<EntityB> EntityBSet;
   ...
}

表B

public class EntityB
    @Id
    private long id;
    @Column(name = "B_SIREN")
    private String siren;    
    @Column(name = "B_NDA")
    private String nda;
}

Hibernate生成3个表:TABLE_A,TABLE_B和包含A_NDA,A_SIREN,B_ID的关联表。如何只生成2个表。

我的目标是在不需要关联表的情况下找到与实体A(entityA.getEntityBSet())相同的一对SIREN / NDA关联的entityB列表,因为我的表由外部批处理提供。

entityA = entityARepository.findOne(new SirenNdaKey("nda_test1", "siren_test1"));
entityA.getEntityBSet()  // this list is always empty

1 个答案:

答案 0 :(得分:3)

这是正确的源代码,我应该使用@JoinColumns代替@PrimaryKeyJoinColumns

public class EntityA{

   @EmbeddedId  
   private SirenNdaKey sirenNda;

   @OneToMany(fetch = FetchType.LAZY)
      @JoinColumns({ @JoinColumn(name = "B_SIREN", 
    referencedColumnName = "A_SIREN"),
      @JoinColumn(name = "B_NDA", referencedColumnName = "A_NDA") 
    })
   private Set<EntityB> EntityBSet;
   ...
}