Is it possible to add @NodeEntity (or even @RelationshipEntity) annotation from SpringData Neo4j on an interface or abstact class or their fields? If not, how do you manage these situations?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Definitely you can do that on Abstract classes, and I think it's a good practice in some common cases. Let me give you an example that I'm using in my graph model:
@NodeEntity public abstract class BasicNodeEntity implements Serializable {     @GraphId    private Long nodeId;     public Long getNodeId() {       return nodeId;    }     @Override    public abstract boolean equals(Object o);     @Override    public abstract int hashCode(); }   public abstract class IdentifiableEntity extends BasicNodeEntity {     @Indexed(unique = true)    private String id;     public String getId() {       return id;    }     public void setId(String id) {       this.id = id;    }     @Override    public boolean equals(Object o) {       if (this == o) return true;       if (!(o instanceof IdentifiableEntity)) return false;        IdentifiableEntity entity = (IdentifiableEntity) o;        if (id != null ? !id.equals(entity.id) : entity.id != null) return false;        return true;    }     @Override    public int hashCode() {       return id != null ? id.hashCode() : 0;    } } Example of entity idenifiable.
public class User extends IdentifiableEntity {    private String firstName;    // ...     public String getFirstName() {       return firstName;    }     public void setFirstName(String firstName) {       this.firstName = firstName;    } } OTOH, as far as I know, if you annotate an interface with @NodeEntity, those classes who implement the interface DON'T inherite the annotation. To be sure I've made a test to check it and definately spring-data-neo4j throws an Exception because don't recognize the inherited class neither an NodeEntity nor a RelationshipEntity.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Invocation of init method failed; nested exception is org.springframework.data.neo4j.mapping.InvalidEntityTypeException: Type class com.xxx.yyy.rest.user.domain.User is neither a @NodeEntity nor a @RelationshipEntity Hope it helps
回答2:
@NodeEntity or @RelationshipEntity needs to be defined on POJO or concrete classes. Think it same as @Entity in Hibernate. But do you see any valid use case for annotating Interfaces or Abstract Classes?