简体   繁体   中英

Capturing entity information in custom entity listener

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?

Entity listeners cannot be parameterized. Just make the relevant entities implement an interface, eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM