Spring Framework + Eclipselink +异常翻译机制

时间:2013-08-13 21:04:43

标签: spring eclipselink

这个问题与两年前提出的问题类似here。我正在寻找一些信息,当出现一些常见的数据库问题时,如何处理从Eclipselink 2.5抛出的异常。我得到的是丑陋的org.springframework.transaction.TransactionSystemException,它没有给我任何关于失败的信息。我们以一个简单的实体为例:

@Entity
class Insect(_name: String) {

  def this() = this(null)

  @Id
  @Column(unique = true)
  var name: String = _name
}

同样简单的存储库:

@Repository
@Transactional
class InsectDaoImpl extends InsectDao {
  @PersistenceContext
  var entityManager: EntityManager = _

  override def addInsect(insect: Insect) = entityManager.persist(insect)
}

执行以下代码:

insectDao.addInsect(new Insect("hornet"))
insectDao.addInsect(new Insect("hornet"))

给我:

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "CONSTRAINT_INDEX_8 ON PUBLIC.INSECT(NAME)"; SQL statement:
INSERT INTO INSECT (NAME) VALUES (?) [23505-172]
Error Code: 23505
Call: INSERT INTO INSECT (NAME) VALUES (?)
    bind => [1 parameter bound]
Query: InsertObjectQuery(pl.zientarski.model.Insect@1df202be)

废话!例外本身并未对问题的根源提出任何建设性意见。内部异常首先是特定于数据库的,其次只有异常消息解释了什么是错误的。为了比较,与Hibernate相同的设置提供了这个例外:

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PRIMARY_KEY_8 ON PUBLIC.INSECT(NAME)"; SQL statement:
insert into Insect (name) values (?) [23505-172]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

异常类型即时提供有关正在发生的事情的提示。

当您查看org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect.translateExceptionIfPossible(RuntimeException ex)的源代码时,Eclipselink的工作方式并不令人惊讶。首先,它甚至没有被覆盖以支持Eclipselink特定的异常,其次是从DefaultJpaDialect继承的默认实现来自javax.persistence.PersistenceException的例外。

我想问你解决这个问题的最佳做法是什么。或许我只是看不到那里的解决方案。请让我知道你的建议。

使用Eclipselink 2.5和Spring 3.2.3进行测试

感谢。

0 个答案:

没有答案
相关问题