Hi!
For some reason I need to work with tables with compound keys. The keys have two parts, one is generated by a Postgres sequence (pk) the other is assigned (machine_id). The reason was so that rows generated by different machines can be integrated without conflicts.
Now I would like to map a simple one-to-many relationship. For simplicity, let's have two classes, A and B, B being on the many side.
What I'd like to see is this:
Code:
class Id {
int pk;
int machine_id;
}
class A {
Id id;
Set<B> b;
}
class B {
Id id;
A a;
}
Now in order to have this, I'd like to annotate B.setA() method like this:
Code:
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumns({
@JoinColumn(name="a", referencedColumnName="pk"),
@JoinColumn(name="machine_id", referencedColumnName="machine_id")
})
public A getA() {
return a;
}
This is because only the fields a and machine_id together can identify the column (these two are in the foreign key definition too).
But here is the catch: you have two mappings for the machine_id now, so Hibernate forces you to have the insertable and updateable flags set to false for the column specs before the getA() method, like this:
Code:
@JoinColumn(name="machine_id", insertable=false, updatable=false)
This would be very fine with me, since I dont want to change machine_id there anyway. But hey, you cannot have a compound key with both insertable and non-insertable fields at the same time! So you need to specify these flags for "a" too.
And of course, this results in that even though you set the value for a in an instance of B, it never gets inserted.
The only workaround I found is to have an additional field for inserting, which is mapped to the same field ("a"), and instead of calling b.setA(a), you need to call b.setAId(a.getId().getPk()).
Code:
@Column(name="a")
int aId;
And even though it looks simple here, it gets a lot uglier with classes having a few more external references.
Anyone has any suggestion for mapping these tables in a convenient to use way? E.g. being able to insert/update, but also navigating the relationship the usual way?
Thanks,
Roland