简体   繁体   中英

how to handle transation roll back exception in spring?

What I want is quite simple: validation for a node id.

The project structure is: Controller(endpoint) - Service - DAO. @transaction in Service layer, validation in Service layer as well.

In endpoint, pass in DTO object. Validate node id in service layer and save to neo4j database in DAO layer. In the DTO object(egStudent) I pass in the other node ID(egClass) which is used to set up student and class relationship. Before saving, I do validation for the node(Class) id.

If I use repository.findOne(id) and pass in node ID which exist in database but wrong type. This will raise: org.neo4j.graphdb.NotFoundException: '__type__' property not found for RelationshipImpl #10118 of type 36 between Node[7054] and Node[6726] which will lead to the following exception:

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

If I use following query and pass in node id which does not exist in database

start node1 = node(id)
return node1

org.neo4j.cypher.EntityNotFoundException will be raised and lead to UnexpectedRollbackException as well.

Is there any way I catch these exceptions and return null or false without UnexpectedRollbackException?

Or is there any way I can check Node id exists in database easily?

Fix this by using:

  1. For Node:

      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. For Relationship

      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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM