Create/Update Hibernate association by just providing the foreign key
I have two Hibernate entities named Alpha and Beta, and Alpha has a *-to-one association with Beta. I'd like to create a new Alpha entry in the database, with a reference to an existing Beta. I have the primary id of the Beta entry I want to associate, but I do not have the actual instance. Currently I'm storing Alpha like this (using Spring's HibernateTemplate):
Alpha alpha = new Alpha();
alpha.setBeta(hibernateTemplate.load(Beta.class, betaId));
hibernateTemplate.save(alpha);
I'd like to avoid开发者_如何学Python having to load Beta first, however, as it is an unnecessary query (I don't need alpha.getBeta() to contain the up to date attached entity - ideally Hibernate should replace that with a proxy like with lazy loading). So I tried the following (keep in mind that there exists a Beta entry with betaId):
Alpha alpha = new Alpha();
Beta beta = new Beta(betaId);
alpha.setBeta(beta);
hibernateTemplate.save(beta);
This works, but logging shows that Hibernate still goes and queries Beta in the backend. Even worse, if that association has cascading configured, the empty Beta entry will overwrite the existing one.
So, is there any way to create or update such an association by just providing the foreign key and without Hibernate having to query the associated table? Ideally I'd like to replicate something like this SQL statement:
UPDATE alpha SET beta_id = :beta_id WHERE alpha_id = :alpha_id
HibernateTemplate.load()
delegates to Session.load()
, therefore it should do exactly what you want. Enable SQL logging to make sure that extra queries are not issued.
See also:
- 11.3. Loading an object
精彩评论