Skip to content

Interceptors

DuyHai DOAN edited this page Aug 25, 2017 · 11 revisions

Introduction

To have tighter control on the persistence lifecycle of an entity, you can rely on Interceptors. Each interceptor is called upon a lifecycle event and modifies the entity state.

Below is the list of all possible lifecycle events:

  1. PRE_INSERT
  2. POST_INSERT
  3. PRE_DELETE
  4. POST_DELETE
  5. POST_LOAD

Usage

To use interceptors, you must provide your own implementation of the interface Interceptor<T>:

        
    public interface Interceptor<T> {
    
        boolean acceptEntity(Class<?> entityClass);
        
        public void onEvent(T entity, Event event);
    
        public List<Event> events();
    }

    public enum Event 
    {
      PRE_INSERT, POST_INSERT, PRE_DELETE, POST_DELETE, POST_LOAD;
    }
  • The boolean acceptEntity(Class<?> entityClass) method should be implemented to filter interceptors.
  • The onEvent(T entity) method should be implemented to perform functional logic. The whole raw entity is provided as method argument as well as the current event
  • The List<Event> events() method defines a list of events this interceptor should be triggered for

Example:

	public class UserInterceptor extends Interceptor<User> 
	{
	    
	    public boolean acceptEntity(Class<?> entityClass) {
	        if(entityClass != null) return User.class.equals(entityClass);
	        return false;        
	    }
	    
	    public void onEvent(User entity) {
	        if(entity.getBiography() == null) {
	            entity.setBiography("TO DO");
	        }
	    }
	
	    public List<Event> events() {
	        return Arrays.asList(PRE_INSERT,PRE_UPDATE);
	    }
	}

The above UserInterceptor will update the biography to "TO DO" if it is not set before updating/saving the entity.

Configuration

To register your interceptors with Achilles, you should pass them as parameter to the configuration parameter map:

	
	...
	List<Interceptor<?>> interceptors = Arrays.asList(userInterceptor); 
	configMap.put(EVENT_INTERCEPTORS,interceptors);
	...

Gotchas

There are some gotchas when using interceptors:

Null-check.

Indeed when you craft your own CQL query using the RAW API, you may not select all fields to be retrieved. Consequently the entity will have some null fields when the POST_LOAD interceptors are applied. For safety and to avoid the dreadful NullPointerException, it is strongly recommended to perform null checks in the code of your interceptors.

This recommendation also applies to crud().findById() method since some fields may be null in Cassandra

Primary key

It is absolutely a bad idea to modify the primary key in your interceptors. In most cases there is no sensible reason to do so.

To avoid NullPointerException, Achilles will enforce null check (but not value check) on the primary key after each PRE_INSERT/PRE_DELETE interceptor invocation.

Home

Clone this wiki locally