jpa composite primary key mapping
I have 2 tables as follows:
TABLE_A
-------
A_SIREN
A_NDA
TABLE_B
-------
B_id
B_NDA
B_SIREN
Table A ID is COMPOSITE KEY
SIREN / NDA
Here's the entity 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 will generate 3 tables: TABLE_A, TABLE_B and an association table that contain A_NDA, A_SIREN, B_ID. How do I create only 2 tables.
My object is to find a list of entities related to the same SIREN / NDA pair from object A ( entityA.getEntityBSet()
) without the need for an association table as my tables are supplied with an external batch.
entityA = entityARepository.findOne(new SirenNdaKey("nda_test1", "siren_test1"));
entityA.getEntityBSet() // this list is always empty
+3
source to share
1 answer
This is the correct source code, I should use @JoinColumns
instead@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;
...
}
+3
source to share