我使用PostgreSQL,Hibernate和JPA。 每当有数据库中的一个例外,我得到这样的事情是不是非常有帮助,因为它并没有显示真正出了错DB服务器上。
Caused by: java.sql.BatchUpdateException: Batch entry 0 update foo set ALERT_FLAG='3' was aborted. Call getNextException to see the cause.
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1837)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2754)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 82 more
我想从数据库异常消息出现在应用程序的日志。
我遇到了这篇文章 ,它使用的看点来填充它,否则不会的SQLException的情况下,适当地填充异常链。
有没有办法解决这个问题,而无需使用方面或任何自定义代码。 理想的解决方案只涉及配置文件中的变化。
有没有需要编写任何自定义代码来实现这一点 - Hibernate会默认登录异常的原因。 如果你不能看到这一点,Hibernate日志不能正确设置。 下面是与SLF4J + log4j的,并使用Maven依赖管理的例子。
的src /主/爪哇/ pgextest / PGExceptionTest.java
public class PGExceptionTest {
public static void main(String[] args) throws Exception {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(
"pgextest");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
// here I attempt to persist an object with an ID that is already in use
entityManager.persist(new PGExceptionTestBean(1));
entityManager.getTransaction().commit();
entityManager.close();
}
}
SRC /主/资源/ log4j.properties
log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
SRC /主/资源/ META-INF / persistence.xml中
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pgextest">
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/pgextest"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.jdbc.batch_size" value="5"/>
</properties>
</persistence-unit>
</persistence>
的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pgextest</groupId>
<artifactId>pgextest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.9.Final</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
然后执行的主要方法将记录以下内容:
ERROR [main] - Batch entry 0 insert into PGExceptionTestBean (label, id) values (NULL, '1') was aborted. Call getNextException to see the cause.
ERROR [main] - ERROR: duplicate key value violates unique constraint "pgexceptiontestbean_pkey"
这也许值得一提的是,您可以禁用JDBC批处理,通过属性设置包装原始异常hibernate.jdbc.batch_size
到0
(不用说了你可能不希望这样做生产。)
这个工作让我得到这导致了该问题(休眠3.2.5.ga)异常消息:
catch (JDBCException jdbce) {
jdbce.getSQLException().getNextException().printStackTrace();
}
对我来说,这个例外是一个PersistenceException下,所以我不得不这样做:
try {
//...
} catch (javax.persistence.PersistenceException e) {
log.error(((java.sql.BatchUpdateException) e.getCause().getCause()).getNextException());
}
我觉得看点编程是一个更好的解决方案来解决这类问题。
但是,如果你要编写自定义代码来做到这一点,你可以通过它赶上了SQLException并循环并记录每个异常。 像这样的东西应该工作。
try {
// whatever your code is
} catch (SQLException e) {
while(e!= null) {
logger.log(e);
e = e.getNextException();
}
}
try {
// code
} catch (SQLException e) {
for (Throwable throwable : e) {
log.error("{}", throwable);
}
}
以防万一,如果恰巧你是从JUnit测试中得到这个例外您可以将JUnit的例外与TestRule
(这是由源激发ExpectedException
TestRule
)
public class HibernateBatchUnwindRule implements TestRule {
private boolean handleAssumptionViolatedExceptions = false;
private boolean handleAssertionErrors = false;
private HibernateBatchUnwindRule() {
}
public static HibernateBatchUnwindRule create(){
return new HibernateBatchUnwindRule();
}
public HibernateBatchUnwindRule handleAssertionErrors() {
handleAssertionErrors = true;
return this;
}
public HibernateBatchUnwindRule handleAssumptionViolatedExceptions() {
handleAssumptionViolatedExceptions = true;
return this;
}
public Statement apply(Statement base,
org.junit.runner.Description description) {
return new ExpectedExceptionStatement(base);
}
private class ExpectedExceptionStatement extends Statement {
private final Statement fNext;
public ExpectedExceptionStatement(Statement base) {
fNext = base;
}
@Override
public void evaluate() throws Throwable {
try {
fNext.evaluate();
} catch (AssumptionViolatedException e) {
optionallyHandleException(e, handleAssumptionViolatedExceptions);
} catch (AssertionError e) {
optionallyHandleException(e, handleAssertionErrors);
} catch (Throwable e) {
handleException(e);
}
}
}
private void optionallyHandleException(Throwable e, boolean handleException)
throws Throwable {
if (handleException) {
handleException(e);
} else {
throw e;
}
}
private void handleException(Throwable e) throws Throwable {
Throwable cause = e.getCause();
while (cause != null) {
if (cause instanceof BatchUpdateException) {
BatchUpdateException batchUpdateException = (BatchUpdateException) cause;
throw batchUpdateException.getNextException();
}
cause = cause.getCause();
};
throw e;
}
}
然后添加规则测试用例
public class SomeTest {
@Rule
public HibernateBatchUnwindRule batchUnwindRule = HibernateBatchUnwindRule.create();
@Test
public void testSomething(){...}
}
如果由于某种原因,你遇到从卡夫卡连接此异常,可以将batch.size属性设置为0(暂时)是为了揭示水槽工人遇到例外。
文章来源: Call getNextException to see the cause : How to make Hibernate / JPA show the DB server message for an exception