畢設20200528 Neo4jRepository的使用,findAll方法的注意點

Neo4jRepository是繼承了Spring data的CrudRepository的,所以是在CrudRepository的基礎上針對Neo4j做了擴展的。

初步使用的實驗是,你能想到的CRUD的方法,基本不用你自己寫Cypher(也就是Neo4j的SQL)。
比如要模糊查詢:

MATCH (a:Artifact) WHERE a.artifactId CONTAINS 'red' return a 

那麼,對應地你只要在你自己定義的Repository中繼承Neo4jRepository,就可以像堆積木一樣寫出你的get請求對應的方法名“findAllByArtifactIdContains”,那麼這個方法名就對應了上面的查詢語句,且不用我們自己顯式用@Query在接口方法上寫出查詢語句

//@Query("MATCH (a:Artifact) WHERE a.artifactId CONTAINS $artifactId RETURN a")
List<Artifact> getAllByArtifactIdContains(String artifactId);

findAll在Neo4jRepository裏面有多種重載
如果你在一個圖數據庫裏面使用不帶參數的findAll()方法,那麼就會報下面的錯誤。大概就是因爲你Node之間是彼此關聯的,findAll()方法執行的Cypher如下:

MATCH (n:`Organization`) WITH n RETURN n,[ [ (n)<-[r_h1:`HAS_ORG`]-(a1:`Artifact`) | [ r_h1, a1 ] ] ]

這個Cypher在數據庫裏面會查到Organization和Artifact兩個節點和他們彼此間的關係。如下,
在這裏插入圖片描述
那麼,這邊不加上控制,就會通過a去找到g,在通過g去找到a,直接導致stackOverFlowError內存溢出了。

Swagger上面call這個findAll方法,直接返回這樣一個結果
在這裏插入圖片描述
表示,雖然Cypher正確執行也拿到了結果,大師數據過大,Swagger無力將其轉換成JSON,只能給你看個原數據。

顯示的數據如下,基本就是重複數據無線循環:

can't parse JSON.  Raw result:

[{"id":5,"name":"redhat","url":"redhat-7.org","artifacts":[{"id":20,"groupId":"neo4j","artifactId":"neo4j","version":"1.2.3","availability":true,
"scope":null,"artifacts":[],"dependencies":[],"parent":null,"licenses":[],"organization":
{"id":5,"name":"redhat","url":"redhat-7.org","artifacts":
[{"id":20,"groupId":"neo4j","artifactId":"neo4j","version":"1.2.3","availability":true,
"scope":null,"artifacts":[],"dependencies":[],"parent":null,"licenses":[],"organization":
{"id":5,"name":"redhat","url":"redhat-7.org","artifacts":
[{"id":20,"groupId":"neo4j","artifactId":"neo4j","version":"1.2.3","availability":true,
"scope":null,"artifacts":[],"dependencies":[],"parent":null,"licenses":[],"organization":
{"id":5,"name":"redhat","url":"redhat-7.org","artifacts":
[{"id":20,"groupId":"neo4j","artifactId":"neo4j","version":"1.2.3","availability":true,
"scope":null,"artifacts":[],"dependencies":[],"parent":null,"licenses":[],"organization":
{"id":5,"name":"redhat","url":"redhat-7.org","artifacts":
...

解決方法:
其實就給這個findAll查詢加個深度就可以了

artifactRepository.findAll(0);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章