【发布时间】:2015-07-03 08:38:29
【问题描述】:
是否可以在接口或抽象类或其字段上从SpringData Neo4j 添加@NodeEntity(甚至@RelationshipEntity)注释?如果没有,您如何处理这些情况?
【问题讨论】:
标签: neo4j spring-data spring-data-neo4j
是否可以在接口或抽象类或其字段上从SpringData Neo4j 添加@NodeEntity(甚至@RelationshipEntity)注释?如果没有,您如何处理这些情况?
【问题讨论】:
标签: neo4j spring-data spring-data-neo4j
你当然可以在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
希望对你有帮助
【讨论】:
String id 的用法:这是为什么呢?是否与hash() 甚至equals() 有关?
UUID.randomUUID().toString(),并在将每个实体保存在 BeforeSaveEvent 中之前生成它们。我的 SO 问题中有一个 example。希望对你有帮助
@NodeEntity interface ComparableObject 和其他实现此接口的实体怎么办?如果这些实体也被注释为@NodeEntity怎么办?
MyClass [or MyInterface] is neither a @NodeEntity nor a @RelationshipEntity 的异常。
@NodeEntity 或@RelationshipEntity 需要在 POJO 或具体类上定义。认为它与 Hibernate 中的 @Entity 相同。 但是您是否看到任何用于注释接口或抽象类的有效用例?
【讨论】:
@NodeEntity abstract class User;这样,你就知道每个扩展这个类的类,比如UserPerson或者UserOrganization,在图中总是一个Node。此外,如果您有常见的注释字段,例如简单的@GraphId Long id 或更复杂的情况@RelatedTo(...) private Set<Message> messages,它也很有用。管理这些案例的标准方法是什么?