为Spring Data Neo4j

时间:2018-04-28 13:22:46

标签: java neo4j spring-data-neo4j

我有两个实体:

@NodeEntity
public class User {

@Id
@GeneratedValue
private Long id;

private String firstName;

private String lastName;

@Relationship(type = "IN")
private Department department;

}

@NodeEntity
public class Department {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
}

我需要一个搜索firstName,lastName和department id的逻辑。 我查看了存储库方法并找不到解决方案,因为我的查询是动态的(搜索查询中可能有0或3个参数)。

这项任务的最佳解决方案是什么?现在,我设法使用手动查询构建和Session对象,如下所示:

StringBuilder builder = new StringBuilder("MATCH (user:User)-[:IN]->(department:Department) WHERE ");
 if (departmentId != null) {
        builder.append(String.format("ID(department) = %s", departmentId));
        builder.append(" AND ");
 }
 ...
List<User> userList  =  Lists.newArrayList(session.query(User.class,builder.toString(), Collections.emptyMap()));

但它看起来很难看,我想找到更好的解决方案。 谢谢!

1 个答案:

答案 0 :(得分:1)

使用CASE expressions,您可以获取密码查询中的所有逻辑:

MATCH (U:User)-[:IN]->(D:Department) WHERE
  CASE WHEN NOT $firstName IS NULL 
    THEN U.firstName = $search.firstName 
    ELSE TRUE 
  END AND
  CASE WHEN NOT $lasrName IS NULL 
    THEN U.lastName = $lastName 
    ELSE TRUE 
  END AND
  CASE WHEN NOT $departmentId IS NULL 
    THEN ID(D) = $departmentId 
    ELSE TRUE 
  END    
RETURN *