简体   繁体   中英

spring-data dynamic entity annotations

I have an entity class to be used in spring-data persistence

@Persistent 
public class Foo{
  Bar bar;
}

Since we are switching between Couchbase and Aerospike persistence layers - this class is going to be used in both of them for some time. That is why I have these class in common maven module. Module structure looks like this

  • persistence-common
  • persistence-aero
  • persistence-couch

My idea here is to have spring-data CouchbaseRepository and AerospikeRepository in corresponding modules both implementing Repository class from common

public interface Repository {
   save(Foo foo);
}

And I have one problem. I need my Foo.class to have expiry option which could be achieved by adding either @org.springframework.data.aerospike.mapping.Document(expiration = ...) annotation for aerospike or @org.springframework.data.couchbase.core.mapping.Document(expiryExpression = ...) annotation for couchbase. And I don't want this annotations to be in common module. I need them to be added to Foo class dynamically, depending on which of the modules (couchbase or aerospike or both) are included in runtime.

Can I somehow achieve such flexibility?

My two cents. Use an interface for your base model inside persistence-common .

public interface Foo {
   Bar getBar();
}

You can now implement it once for the persistence-aero module

@Document(expiration = 1000)
public class AerospikeFoo implements Foo {
   @Override
   public Bar getBar() { ... }
}

And once for persistence-couch

@Document(expiryExpression = "...")
public class CouchbaseFoo implements Foo {
   @Override
   public Bar getBar() { ... }
}

This will make clear their usage scope and intent.
You don't need to re-use @Persistent , as it's already inherited with @Document .

If they share some kind of functionality, create a class to delegate to, on the line of PersistenceFooHelper . Do not extend an abstract class .

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