使用 neo4j OGM 按其属性名称查找节点



我有我的技能集群类,如下所示

public class SkillCluster {
@Id @GeneratedValue
private Long id;
private String Name;
private String CleanedText;
@Relationship(type = "BelongsTo", direction = Relationship.INCOMING)
private Set<Skill> contains = new HashSet<>();
}

其对应的DAO类

import org.neo4j.ogm.session.Session;
import com.models.GenericDAO;
public class SkillClusterDAO extends GenericDAO<SkillCluster>{
public SkillClusterDAO(Session session) {
super(session);
}
protected Class<SkillCluster> getEntityType() {
return SkillCluster.class;
}   
}

和我的泛型DAO类作为

public abstract class GenericDAO<T> {
private static final int DEPTH_LIST = 0;
private static final int DEPTH_ENTITY = 1;  
private Session session;
public long filterCount(Iterable<Filter> filters){
return session.count(getEntityType(), filters);
}
public T find(Long id) {
return session.load(getEntityType(), id, DEPTH_ENTITY);
}
public T find(String name) {
return session.load(getEntityType(), name, DEPTH_ENTITY);
}
public void delete(Long id) {
session.delete(session.load(getEntityType(), id));
}
public void createOrUpdate(T entity) {
session.save(entity, DEPTH_ENTITY);
//return find(entity.id);
}
protected abstract Class<T> getEntityType();
public GenericDAO(Session session) {
this.session = session;
}
}

我想通过匹配 Node 属性来获取群集节点Name通过执行此操作

skillSessionFactory = new SessionFactory(skillConfiguration, "com.skill.models");
skillSession = skillSessionFactory.openSession();
skillClusterDAO = new SkillClusterDAO(skillSession);
SkillCluster clusterNode = skillClusterDAO.find(cluster_name);

我收到以下错误 -

java.lang.IllegalArgumentException: Supplied id must be of type Long (native graph id) when supplied class does not have primary id - com.models.SkillCluster

您有此错误是因为name属性不是Long

即使您的 name 属性也是Long,它也不起作用,因为它会被获取错误的节点。

session.load(...)适用于内部节点 ID,或者将属性标记为@Id或主索引@Index(primary = true)

如果需要按主键以外的属性查找节点,则可以使用session.loadAll(...)with filter。

public abstract class GenericDAO<T> {
...
import java.util.Collection;
import java.util.Optional;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.ogm.cypher.Filter;
...
public T find(Long id) {
return session.load(getEntityType(), id, DEPTH_ENTITY);
}
public T find(String name) {
final String propertyName = "name";
Filter filter = new Filter(propertyName, name);
Collection<T> results = session.loadAll(getEntityType(), filter, DEPTH_ENTITY);
if( results.size() > 1)
throw new CustomRuntimesException("Too results found");
Optional<T> entity = results.stream().findFirst();
return entity.isPresent() ? entity.get() : null;
}
...
}

最新更新