Interceptors in Hybris

We know that Models in Hybris are the representation of database tables and we often use models to save data in database and to load data from Database. These models we use in Hybris has its own lifecycle managed by ModelService.

There are several methods provided by ModelService to represent its lifecycle.
Example : Create, Save, Update, Load, Remove.When we call any of these ModelService method, it just follows its Lifecycle and completes the execution. Example : Save method save the model data in Database.

The interceptors have the ability to interrupt the lifecycle of a model and execute some code and then allow the model to continue its lifecycle.

Life Cycle of a Model

When we use interceptors ?

We need to use interceptors whenever we want to perform some action during the life cycle of a model.
Example : If we need to validate the model data before saving in database

We can see the main use of interceptors in some scenarios as mentioned below:
  • Auditing the details while saving the model data.
  • Validating the model data before saving.
  • Restrict data from deleting or modifying based on some conditions.
  • We can even modify the model before saving it using interceptors.

Types of interceptors in Hybris:-

There are 5 main interceptors provided by Hybris:
  • Init Defaults interceptor
  • Prepare interceptor
  • Validate interceptor
  • Load interceptor
  • Remove interceptor
Init Defaults interceptor:-

This interceptor is represented by an interface Called “InitDefaultsInterceptor”. This is called when a model needs to be filled with its default values.

We can use this interceptor to fill the model with additional default values, apart from the values defined in items.xml file

Prepare Interceptor:-

This interceptor is represented by an interface called “PrepareInterceptor”. This interceptor is called before model is saved to the database and before it is validated by the validate interceptor. We can use this to add values to the model or modify existing before they are saved to the database.

Validate Interceptor:-

This interceptor is represented by an interface called “ValidateInterceptor”. This is called before a model is saved to the database after is been prepared by the Prepare interceptors.

Load Interceptor:-

This interceptor is represented by an interface called “LoadInterceptor”. This is called when we retrieve the model from the database.

Remove Interceptor:-

This interceptor is represented by an interface called “RemoveInterceptor”. This is called before a model is removed/deleted from the database.

Leave a comment