Capturing entity information in custom entity listener

267 views Asked by At

I would like a custom entity listener to generate an auto-incremented alias for a few of the entities.

I have implemented one util class in order to generate auto incremented alias for the entities in a distributed environment as follows:

@Component
public class AutoIncrementingIdGenerationUtil {

  private final RedisTemplate<String, Object> redisTemplate;

  public AutoIncrementingIdGenerationUtil(
      RedisTemplate<String, Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  public String getNextSequenceNumber(String keyName) {
    RedisAtomicLong counter = new RedisAtomicLong(keyName,
        Objects.requireNonNull(redisTemplate.getConnectionFactory()));
    return counter.incrementAndGet();
  }
}

Now, I have several entities in my application, for a FEW OF ENTITIES, I would like to generate the alias.

So I am writing my own custom entity listener as follows:

@Component
public class CustomEntityListener<T> {

  private final AutoIncrementingIdGenerationUtil autoIncrementingIdGenerationUtil;


  public CustomEntityListener(
      AutoIncrementingIdGenerationUtil autoIncrementingIdGenerationUtil) {
    this.autoIncrementingIdGenerationUtil = autoIncrementingIdGenerationUtil;
  }

  @PrePersist
  void onPrePersist(Object entity) { <----HERE I WOULD LIKE TO CAST TO CONCRETE ENTITY TYPE, 
    if(StringUtils.isBlank(entity.getAlias())) {
       entity.setAlias(autoIncrementingIdgenerationUtil.getNextSequenceNumber(entity.getEntityType());
  }
}

As mentioned above, all of the entities do not have an alias attribute. I am not getting any proper idea regarding how to do this. One bad idea is to use getTEntityype(). But in this case, it would be too many if-else and typecast accordingly, which will not look good. Any better idea regarding how to do it?

Another related question in the same context, if I have an entity having a @PrePersist function already, will the function defined in entity listener override this, OR will both of them run?

1

There are 1 answers

0
crizzis On

Entity listeners cannot be parameterized. Just make the relevant entities implement an interface, e.g. Aliased, with a setAlias() method. You'll then have a single type to cast to.

Also, why use Redis? Doesn't your DB have sequences?