Interceptors in Hibernate

By Eugenia Pérez | 7 February, 2015

We all know ORMs and why they were developed but apart from mapping relational data to objects and all its possible relations between them they offer some other features aside. One of the most full-featured ORMs in the market is Hibernate, which is the most successful in the Java platform y has been ported to other programming languages like .NET. Among these extra features are Interceptors.

Interceptors are useful to perform customized actions before, while or after Hibernate events. To do so we just need to choose the desired event between the eighteen existent. Some of them are onDelete, onLoad, onSave, etc. These are methods of the Interceptor Interface. Given that we usually only need to implement some of them there is an abstract class called EmptyInterceptor from which can inherit in order to avoid implementing all of them.

So to create our brand-new interceptor we just need to create a new class which extends from EmptyInterceptor and override the events we want. For example, onSave if what we need is to carry out some action when Hiberate saves an entity to the database.

In the previous example we are making sure that we print out a message to the console every time a user is saved. Keep an eye on the needed check in order to test that the entity which is about to be saved is a User. This is necessary because the parameter comes as an object.

Once this is done the session has to be initialized with the interceptor wired up:

With this set every time we call the save method passing a User, a message will be flushed to the console.

This is just a brief summary of one of the many things I am teaching right now in a Hibernate and Spring course. Keep in touch to find more about it.

Anyway, you might be interested in searching for more about this on my slides, at the end of this section:

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather