简体   繁体   中英

Spring JPA - entity detached? on exceptions?

I'm not sure if I'm asking it right, but I've got a method that's transactional, and within that I fetch a list of items. Now, while processing one of the items, I encounter an invalid data usage exception[null is passed to a repository, and fine one throws this exception which is fine], and upon getting that exception, I catch it, and mark the item being processed 'failed'. The transactional method ends but the changes do not go through.

@Transactional
public void method(){    
  try{
    List items = itemRepo.getItems(NOT_SUBMITTED);
    for(Item item: items){
      processItem(item); //this is where the exception happens
    }
  }
  catch(Exception e){
    item.setStatus(FAILED) // this doesn't go through to the db
  }
}

private void processItem(Item item){
  otherRepo.findOne(item.X); //item.X is null, and I get "invalid data usage" exception
}

I think the object somehow is getting detached; not sure why. I did a test throwing an exception myself in the try block, worked perfectly. The status was reflected properly.

I tried grabbing this object again doing itemRepo.findOne(item).setState(FAILED), didn't work. I tried, itemRepo.save(item) - didn't work.

Any pointers?

Thanks

The exception is being thrown by the JPA implementation, which also sets the transaction status to setRollbackOnly. That's why you can save the failed state when it's you throwing the exception.

Once the JPA entityManager throws an exception it's done, you can't use that entityManager anymore. Saving the item status as failed would have to be in a separate transaction using a different entityManager instance.

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