Java 如何在Spring Boot中使用EntityManager处理异常

Java 如何在Spring Boot中使用EntityManager处理异常,java,spring,spring-boot,jpa,exception,Java,Spring,Spring Boot,Jpa,Exception,我有dao层: @Transactional public class DatabaseCollectionDao implements IDatabaseCollectionDao { @PersistenceContext private EntityManager entityManager; @Override public void create(Collection collection) { entityManager.pe

我有dao层:

@Transactional
public class DatabaseCollectionDao implements IDatabaseCollectionDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void create(Collection collection) {
           entityManager.persist(collection);
    }
}
它可以正常工作,但是:

  • 当数据库不可用时,我有SocketException
  • 当数据库包含重复键时,我有SQLIntegrityConstraintViolationException
  • 我正在尝试在创建方法中尝试/捕获它:

    @Override
        public void create(Collection collection) {
               try{
                   entityManager.persist(collection);
               } catch (SQLIntegrityConstraintViolationException e){
                   //do smth
               }
        }
    
    但是Intellij说它是从不抛出的
    当我试图尝试/捕获异常时,我有未预料的回滚异常

    如何使用JPA entityManager处理异常?

    更新:尝试删除@Transactional时没有任何结果


    顺便说一句,我试着在更高的层次上抓住它。我不知道我能做些什么来解决这个问题

    创建customException处理程序扩展ResponseEntityExceptionHandler@ExceptionHandler(ConstraintViolationException::class)fun handleConstraintViolation(例如:ConstraintViolationException,request:WebRequest):ResponseEntity{}此kotlin代码片段u可以轻松转换为java—

    实体。持久化(实体)-此代码正确吗?是的,它工作正常。但是,当我停止db并尝试再次发送请求或持久化此实体(具有相同的id)时,我遇到了这样的问题可能您正在考虑
    Entitymanager::persist
    ?哦,对不起,当然。entityManager.persist(实体);请出示您的statcktrace的相关部分