Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jpa one to many composite primary key mapping

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
like image 354
rennajihi Avatar asked Apr 28 '17 14:04

rennajihi


People also ask

How do we configure composite primary key in Hibernate JPA?

There are two options to do this: The first approach – is to use the @Embeddable class, which contains all fields representing a composite key. We should create a field in the JPA entity of this type and annotate it with @EmbeddedId . Another option for composite key mapping - @IdClass .

What is JPA one to one mapping?

The One-To-One mapping represents a single-valued association where an instance of one entity is associated with an instance of another entity. In this type of association one instance of source entity can be mapped atmost one instance of target entity.


1 Answers

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;
   ...
}
like image 154
rennajihi Avatar answered Oct 15 '22 12:10

rennajihi