jpa one to many composite primary key mapping

Rachid Ennaj picture Rachid Ennaj · Apr 28, 2017 · Viewed 11.6k times · Source

I have 2 tables as follows :

TABLE_A
-------
A_SIREN
A_NDA

TABLE_B
-------
B_id    
B_NDA
B_SIREN

The id of table A is a COMPOSITE KEY SIREN/NDA

Here's the entities code.

Key class

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

TABLE 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;
   ...
}

TABLE B

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

Hibernate generate 3 tables : TABLE_A, TABLE_B and association table that contain A_NDA, A_SIREN, B_ID. How can I do to generate only 2 tables.

My objectif is to find a list of entityB associated to the same couple SIREN/NDA from entity A (entityA.getEntityBSet()) without the need of the association table, because my tables are supplied by external batch.

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

Answer

Rachid Ennaj picture Rachid Ennaj · May 2, 2017

This is the correct source code, I should use @JoinColumns instead of @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;
   ...
}