在接口/抽象类上使用@NodeEntity

时间:2015-04-24 16:20:14

标签: neo4j spring-data spring-data-neo4j

是否可以在@NodeEntity上在接口或abstact类或其字段中添加@RelationshipEntity(或甚至SpringData Neo4j)注释?如果没有,你如何处理这些情况?

2 个答案:

答案 0 :(得分:3)

你绝对可以在Abstract classes上做到这一点,我认为在一些常见情况下这是一个很好的做法。让我举一个我在图模型中使用的例子:

@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;
   }
}

实体可识别的例子。

public class User extends IdentifiableEntity {
   private String firstName;
   // ...

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
}

OTOH,据我所知,如果使用@NodeEntity注释接口,那些实现接口的类不会继承注释。为了确保我已经进行了测试以确定它并且肯定spring-data-neo4j会抛出异常,因为无法识别继承的类既不是NodeEntity也不是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

希望有所帮助

答案 1 :(得分:0)

@NodeEntity或@RelationshipEntity需要在POJO或具体类上定义。和Hibernate中的@Entity一样。 但是,您是否看到了用于注释接口或抽象类的任何有效用例?