Hibernate @NotFound - How to handle broken foreign key reference

Опубликовано: 07 Июль 2022
на канале: Thorben Janssen
4,257
104

Some table models don’t enforce their foreign key references by a foreign key constraint. This is a bad practice that often leads to foreign key references that point to non-existing records. When Hibernate tries to resolve such a broken reference, it throws an EntityNotFoundException. You should, therefore, define a foreign key constraint for every foreign key reference.

But after someone decided against using foreign key constraints and deployed the application to production, that decision is often hard to reverse. And that puts you in the position where you need to build a persistence layer that can handle associations [https://thorben-janssen.com/associati...] that reference a non-existing record.
By default, Hibernate throws an exception if it tries to resolve a broken foreign key reference. The best way to fix this is, of course, to clean up your database and fix your foreign key references. But if that’s not an option, you need to decide if you:
want to handle an EntityNotFoundException every time you call the getter method of a potentially broken association or
use Hibernate’s @NotFound annotation to tell Hibernate to fetch a potentially broken association and ignore it or throw a FetchNotFoundException when instantiating your entity object.


Links mentioned in the video:
https://thorben-janssen.com/hibernate...
https://thorben-janssen.com/associati...
https://thorben-janssen.com/standardi...
https://thorben-janssen.com/entity-ma...
https://thorben-janssen.com/hibernate...
https://thorben-janssen.com/ultimate-...
https://thorben-janssen.com/best-prac...
https://thorben-janssen.com/hibernate...



Like my channel? Subscribe!
➜ http://bit.ly/2cUsid8

Read the accompanying post: https://thorben-janssen.com/hibernate...

Want to connect with me?
Blog: https://thorben-janssen.com/
Twitter:   / thjanssen123  
Facebook:   / thorbenjanssenofficial  
Linkedin:   / thorbenjanssen