1

This is similar to the question here:

Best practice for working with Foreign key fields

but I'm wondering whether there is any way to automatically enforce this kind of logic. When I perist a new record in the "many" table, that has a foreign key in "one" table, I'd like hibernate to automatically load the referenced entity and check that it exists, and access that entity's fields (for validation purposes).

Any way to do this just through annotations?

Community
  • 1
  • 1
chrismarx
  • 11,488
  • 9
  • 84
  • 97

1 Answers1

2

That's what you do by default when persisting a Many:

One one = (One) session.get(One.class, oneId); // get the one entity from the database
Many many = new Many();
many.setOne(one);
session.save(many);

If you just need a reference to the one, without actually loading it from the DB, use session.load() instead of session.get().

Whatever you do, only the database can guarantee the coherence of your data (since another transaction could delete the one after you've loaded it and attached to the many), so you need a foreign key constraint in database.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I'm using Spring Roo, which uses Spring Data JPA and there's automatic CRUD scaffolding, so when I try to create a new record for "many", it just calls: if (entityInformation.isNew(entity)) { em.persist(entity); return entity; } else { return em.merge(entity); } – chrismarx Oct 18 '12 at 13:44
  • is that wrong? should a platform like that take into consideration the manytoone nature of the entity? – chrismarx Oct 18 '12 at 18:46
  • It's not wrong, it's just that you need to populate the one association before calling the above method. – JB Nizet Oct 18 '12 at 20:39