Use @NodeEntity on interface/abstract class

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!