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?
That’s what you do by default when persisting a Many:
If you just need a reference to the one, without actually loading it from the DB, use
session.load()instead ofsession.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.