簡體   English   中英

春季如何處理交易回滾異常?

[英]how to handle transation roll back exception in spring?

我想要的很簡單:驗證節點ID。

項目結構為:控制器(端點)-服務-DAO。 服務層中的@transaction,以及服務層中的驗證。

在端點中,傳遞DTO對象。 驗證服務層中的節點ID,並保存到DAO層中的neo4j數據庫。 在DTO對象(例如,Student)中,我傳入另一個用於建立學生和班級關系的節點ID(例如,Class)。 保存之前,我會驗證node(Class)id。

如果我使用repository.findOne(id)並傳入數據庫中存在但類型錯誤的節點ID。 這將引發: org.neo4j.graphdb.NotFoundException: '__type__' property not found for RelationshipImpl #10118 of type 36 between Node[7054] and Node[6726] ,這將導致以下異常:

nested exception is org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException: Failed to commit, transaction rolledback

如果我使用以下查詢並傳遞數據庫中不存在的節點ID

start node1 = node(id)
return node1

會引發org.neo4j.cypher.EntityNotFoundException並導致UnexpectedRollbackException。

有什么辦法可以捕獲這些異常並在沒有UnexpectedRollbackException的情況下返回null或false?

還是有什么方法可以輕松檢查數據庫中是否存在節點ID?

使用以下方法解決此問題:

  1. 對於節點:

      Node node = neo4jTemplate.getNode(id); String type = (String) node.getProperty("__type__"); if (!type.equals(nodeClass.getName())) { throw new ResultNotFoundException("No such object (" + nodeClass.getSimpleName() + ": id=" + id + ") in database"); } return neo4jTemplate.projectTo(node, nodeClass); 
  2. 對於關系

      Relationship relationship = neo4jTemplate.getRelationship(id); String type = (String) relationship.getProperty("__type__"); if (!type.equals(nodeClass.getName())) { throw new ResultNotFoundException("No such object (" + nodeClass.getSimpleName() + ": id=" + id + ") in database"); } return neo4jTemplate.projectTo(relationship, nodeClass); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM