1. 程式人生 > >訪問Neo4j spring-data-neo4j入門 (二)@Query 複雜查詢

訪問Neo4j spring-data-neo4j入門 (二)@Query 複雜查詢

本文在訪問Neo4j spring-data-neo4j入門 (一) 基礎上成文,因此請先閱讀訪問Neo4j spring-data-neo4j入門 (一)

我們在上一篇提到使用@Query完成複雜查詢,如同我們的業務一樣,使用簡單的比較大小、日期範圍無法完成業務需要,特別是當我們需要在多個關係中進行查詢時,返回的物件也需要包括關聯的內容。例如返回Movie的所有參演者,就需要Person物件的name等資訊。因此返回的物件也不再是簡單的domain物件,而是複雜的組合物件。筆者這裡以Person為例。實際中可以使用map等。

示例程式碼

我們只需要在自己的Repository實現類上完成@Query註解即可。

public interface PersonRepository extends Neo4jRepository<Person, Long> , CustomizedRepository<Person> {

	Person findByfirstName(@Param("firstName") String firstName);

	Collection<Person> findByfirstNameLike(@Param("firstName") String firstName);

	// returns a Page of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter.
@Query(value = "MATCH (movie:Movie {title:{0}})<-[:ACTED_IN]-(p:Person) RETURN p", countQuery= "MATCH (movie:Movie {title:{0}})<-[:ACTED_IN]-(p:Person) RETURN count(p)") Page<Person> getActorsThatActInAmoviesFromTitle(String movieTitle, Pageable pageable ); }

我們可以看到需要傳入的引數主要是movieTitle, 然後他作為{0}會在MATCH (movie:Movie {title:{0}})<-[:ACTED_IN]-(p:Person) RETURN p中使用到。 因為我們使用Pageable 物件,因此需要提供計算count的cypher

執行效果

完成的程式碼在這裡`,歡迎加星,fork,注意我的程式碼中有CustomizedRepositoryImpl這個是我為了做其他demo新增的, 不是使用@Query註解需要的類. 你可以把CustomizedRepository都刪除了。
在這裡插入圖片描述