@NotFound(action=NotFoundAction.IGNORE) annotation Example

In this example we will see one more important annotation of hibernate which is @NotFound annotation. We have seen one to many and many to one relationship in previous hibernate tutorials. Let’s understand the problem first and then how @NotFound annotation help in overcomming the problem. Here is scinario of our previous example of one to many and many to one relationship .

many to one relatioship dept and course

many to one relatioship dept and course


Let we have saved course object and its associated department object. Now suppose after some time inconsistancy has happened with database and some record of course table either altered or deleted along with primary key. Now when we fetch department record from department table and then try to access associated course record with this deparment record which is not present in course table then hibernate will throw an exception and say that no associated record found.

Now see this with small program.

If fetch type of Course is fetch=FetchType.LAZY then hibernate will trow exception with folloing line

Course course2 = department.getCourse();

If fetch type of Course is fetch=FetchType.EAGER then hibernate will throw exception at the time when we are fetching deparment object.

Department department = (Department)session.get(Department.class, 1);

Now to spress this exception hibernate provide @NotFound(action=NotFoundAction.IGNORE) annotation.

Now NotFound excpetion will not be thrown with fetch=FetchType.EAGER.


This NotFoundException may occur because of some database inconsistancy.

We can spress this exception by adding @NotFound(action=NotFoundAction.IGNORE) annotation.

This is all in this post of hibernate. In next post of hibernate we will see how we can use inheritance concept of java.

Comments are closed.