Skip to content

Instantly share code, notes, and snippets.

@Leward
Last active February 25, 2016 21:58
Show Gist options
  • Save Leward/9b2999507c89039c6800 to your computer and use it in GitHub Desktop.
Save Leward/9b2999507c89039c6800 to your computer and use it in GitHub Desktop.
Neo4jHelper
@Component
public class Neo4jHelper {
@Autowired
private Neo4jOperations neo4jOperations;
public <T extends DomainComponent> Set<T> queryAsSetWithSingleParam(String cypher, Object param1, Class<T> targetClass, String targetKey) {
Map<String, Object> params = new HashMap<>();
params.put("0", param1);
return queryAsSet(cypher, params, targetClass, targetKey);
}
public <T extends DomainComponent> Set<T> queryAsSet(String cypher, Map<String, Object> params, Class<T> targetClass, String targetKey) {
Result queryResult = neo4jOperations.query(cypher, params);
Set<T> results = new HashSet<>();
for (Map<String, Object> queryResultEntry : queryResult) {
if (!queryResultEntry.containsKey(targetKey)) {
throw new IllegalStateException("target key '" + targetKey + "' not found in query result. ");
}
Object targetObject = queryResultEntry.get(targetKey);
if (!(targetClass.isInstance(targetObject))) {
throw new IllegalStateException("target object is of class " + targetObject.getClass().getName() +
" and should be subclass of " + targetClass.getName());
}
results.add((T) targetObject);
}
return results;
}
public <T extends DomainComponent> T querySingleResult(String cypher, Map<String, Object> params, Class<T> targetClass, String targetKey) {
Set<T> results = queryAsSet(cypher, params, targetClass, targetKey);
if(results.iterator().hasNext()) {
return results.iterator().next();
}
else {
return null;
}
}
public <T extends DomainComponent> T querySingleResultWithSingleParam(String cypher, Object param1, Class<T> targetClass, String targetKey) {
Map<String, Object> params = new HashMap<>();
params.put("0", param1);
return querySingleResult(cypher, params, targetClass, targetKey);
}
}
public class UserRepositoryImpl implements UserRespositoryExtension {
@Autowired
private Neo4jHelper neo4jHelper;
private final static String USER_MAPPED_REL_TYPES = "MANAGE|BELONG_TO|HAS_PHONE|HAS|DEPARTMENT";
@Override
public User findOneById(Long id) {
String cypher = "MATCH (u:User) WHERE id(u) = {0} WITH u " +
"OPTIONAL MATCH p = (u)-[:" + USER_MAPPED_REL_TYPES + "]-() " +
"RETURN u, nodes(p), rels(p) ";
return neo4jHelper.querySingleResultWithSingleParam(cypher, id, User.class, "u");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment