编程语言
首页 > 编程语言> > java-jpa一对多复合主键映射

java-jpa一对多复合主键映射

作者:互联网

我有2张桌子,如下所示:

TABLE_A
-------
A_SIREN
A_NDA

TABLE_B
-------
B_id    
B_NDA
B_SIREN

表A的ID是一个组合键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

解决方法:

这是正确的源代码,我应该使用@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;
   ...
}

标签:composite-key,jpa,hibernate,one-to-many,java
来源: https://codeday.me/bug/20191111/2019802.html