davidmarkcarlson wrote:
Hibernate has some support for what you are describing, but I am not entirely sure how far it goes. What I'll give you is the approach that should be supported by EJB3.0.
If the table/class with the composite id is Slave, and the table it references is Master, then the following code should do what you want:
Code:
@Entity
class Master {
@Id
@Column(name="MASTER_PK")
long id;
@Column(name = "DATA_COL_A")
private Object fieldA;
}
@Entity
class Slave {
@EmbeddedId
private SlavePK id;
@ManyToOne
@JoinColumn(name = "MASTER_FK", referencedColumnName = "MASTER_PK", insertable = false, updatable = false)
private Master master;
@Column(name="DATA_COL_B")
private Object fieldB;
}
@Embeddable
class SlavePK {
@Column(name="MASTER_FK")
private long masterId;
@Column(name="PART2_PK")
private int pkPart2;
@Column(name="PART3_PK")
private String pkPart3;
}
By setting the insertable/updatable properties on the @JoinColumn annotation, you make the reference non-authoritative. This is what you want -- the PK is the authoritative reference (and s.b. immutable).
You'd need to set up the constructors, getter/setters, and delegate methods to ID fields, etc. but this gives the basic idea.
Hibernate does go beyond this and allows a @ManyToOne mapping in the @Embeddable class, but I'm not exactly clear how far you could/should push this.
Good luck
Do you have a sample code to persist an instance of the Slave class? This is how I did in my code, but it doesn't work (it compiles, runs well, produces no error/exception but doesn't insert anything - and I didn't see the INSERT statement in the log file although I turned everything on):
- I created an instance m of Master, persisted it.
- Created an instance s of Slave, created the id for the instance s which contains the id of the instance m.
- If I use entityManager.persist(s), the log file shows no SQL statement.
If I use entityManager.merge(s), the log file has a SELECT sql statement like this:
select ... from Slave slave_0 where slave_0.masterId = ? and slave_0.pkPart2 = ? and slave_0.pkPart3 = ?
and there's no INSERT sql statement as I can see when I persisted the instance m of Master.
Do you have any advice for this case?