How to return multiple fields with Spring Data Neo4j RX?

Viewed 622

I am using Spring Data Neo4j RX. And I have a query like this:

@Query("MATCH (a:Repo)-[:REPO_DEPEND_ON]->(b:Repo) WHERE a.name= $name RETURN a.name, b.name")
String[] getSingleRepoDependencyTo(String name);

I know the return type is wrong here, as it cannot be a String array. But how can I get the result properly, which contains two fields?

I have searched online for a long time but cannot find an answer. The "@QueryResult" annotation is not supported in this RX version yet.

Thanks for your help.

3 Answers

Assuming that you have a mapped @Node Repo with its relationships like

@Node
public class Repo {
    // other things
    String name;
    @Relationship("REPO_DEPEND_ON") Repo repo;
}

and defining this method in a ...extends Neo4jRepository<Repo,...>, you could use Projections.

public interface RepoProjection {

    String getName();

    DependingRepo getRepo();

    /**
     * nested projection
     */
    interface DependingRepo {
        String getName();
    }
}

Important to keep in mind that the returned values should be the nodes and relationship to make it work this way.

You could also remove the custom query and do something like:

RepoProjection findByName(String name)

if you do not have the need for a findByName in this repository for the entity itself.

Take a look here: https://neo4j.github.io/sdn-rx/current/#projections.interfaces

It seems to list exactly what you want. From those docs:

interface NamesOnly {
        String getFirstName();
        String getLastName();
}

interface PersonRepository extends Neo4jRepository<Person, Long> {
        List<NamesOnly> findByFirstName(String firstName);
}

There are some other variations too.

You can use annotation @QueryResult on your expected model. For instance you can do that in this way.

DTO:

import org.springframework.data.neo4j.annotation.QueryResult;
@QueryResult
public class SomeDto {

    private int someInt;
    private SomeObject sobj;
    private double sdouble;
    private AnotherObject anObj;
    //getters setters
}

Neo4jRepository:

public interface DomainObjectRepository extends Neo4jRepository<DomainObject, Long> {

 @Query("MATCH(n:SomeTable) RETURN someInt, sobj, sdouble, anObj") //Return a few columns
    Optional<SomeDto> getSomeDto();
}
Related