Mapping issue with multi-field primary keys using hibernate/JPA annotations
Posted
by Derek Clarkson
on Stack Overflow
See other posts from Stack Overflow
or by Derek Clarkson
Published on 2010-05-31T23:17:57Z
Indexed on
2010/05/31
23:23 UTC
Read the original article
Hit count: 447
Hi all,
I'm stuck with a database which is using multi-field primary keys. I have a situation where I have a master and details table, where the details table's primary key contains fields which are also the foreign key's the the master table. Like this:
Master primary key fields:
master_pk_1
Details primary key fields:
master_pk_1
details_pk_2
details_pk_3
In the Master class we define the hibernate/JPA annotations like this:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idGenerator")
@Column(name = "master_pk_1")
private long masterPk1;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "master_pk_1", referencedColumnName = "master_pk_1")
private List<Details> details = new ArrayList<Details>();
And in the details class I have defined the id and back reference like this:
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride( name = "masterPk1", column = @Column(name = "master_pk_1")),
@AttributeOverride(name = "detailsPk2", column = @Column(name = "details_pk_2")),
@AttributeOverride(name = "detailsPk2", column = @Column(name = "details_pk_2")) })
private DetailsPrimaryKey detailsPrimaryKey = new DetailsPrimaryKey();
@ManyToOne
@JoinColumn(name = "master_pk_1", referencedColumnName = "master_pk_1", insertable=false)
private Master master;
The goal of all of this was that I could create a new master, add some details to it, and when saved, JPA/Hibernate would generate the new id for master in the masterPk1 field, and automatically pass it down to the details records, storing it in the matching masterPk1 field in the DetailsPrimaryKey class. At least that's what the documentation I've been looking at implies.
What actually happens is that hibernate appears to corectly create and update the records in the database, but not pass the key to the details classes in memory. Instead I have to manually set it myself.
I also found that without the insertable=true
added to the back reference to master, that hibernate would create sql that had the master_pk_1 field listed twice in the insert statement, resulting in the database throwing an exception.
My question is simply is this arrangement of annotations correct? or is there a better way of doing it?
© Stack Overflow or respective owner