在使用OpenJPA时调用createEntityManager时,是否可以获得更具体的异常或获得Persistence



在使用OpenJPA连接到Derby数据库时,我遇到了这个PersistenceException,它说无法为Derby EmbeddedDriver驱动程序类获得连接,但这并不重要(我知道如何修复它(:

77  RegistryManagement  INFO   [JavaFX Application Thread] openjpa.jdbc.JDBC - Using dictionary class "org.apache.openjp
a.jdbc.sql.DerbyDictionary".
<openjpa-3.1.2-r66d2a72 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: There were errors i
nitializing your configuration: <openjpa-3.1.2-r66d2a72 fatal user error> org.apache.openjpa.util.UserException: A conne
ction could not be obtained for driver class "org.apache.derby.jdbc.EmbeddedDriver" and URL "jdbc:derby:db".  You may ha
ve specified an invalid URL.
....

重要的是,在这个例外中有这个原因:

....
Caused by: ERROR XJ004: XJ004.C : [0] db
at 
....

是Derby错误代码之一(https://db.apache.org/derby/docs/10.5/ref/rrefexcept71493.html)。

PersistenceException是在调用.createEntityManager()时引发的。当谈到文本长度时,它相当长吗。

我可以通过用try-catch包装.createEntityManager()来捕获PersistenceException,但我不知道如何找到更多关于原因的信息,也就是说。获取错误代码,因为PersistenceException可能由于各种原因而被抛出。我不能用捕获SQLExceptionUserException来包装它,因为我的IDE说该方法不会抛出这些异常。

我试着在那个PersistenceException上调用.getMessage().getCause(),但我收到了几乎相同的长文本。

当我调用.getCause()时,它返回RuntimeException,我可以看到,Derby抛出了SQLException:

....
Caused by: java.sql.SQLException: XJ004.C : [0] db
at 
....

再次调用CCD_ 14返回null。

我不想在整个消息(字符串(中搜索某些错误代码的出现,因为这可能会占用大量资源。我认为这个问题可能不是Derby特有的,并且在使用其他sqldbs时会发生,这可能也会引发一些异常。

我的代码:

public class DatabaseManager
{
private EntityManagerFactory managerFactory;
private EntityManager manager;
public DatabaseManager(String persistenceUnitName, Map<String, String> properties)
{
managerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
try
{
manager = managerFactory.createEntityManager();
}
catch(PersistenceException e)
{
//stuff
}
}
....

EntityManagerFactory是javax.persistence包中的一个接口:

public interface EntityManagerFactory {
public EntityManager createEntityManager();
....

在调试时,在PersistenceExceptions类中发现了这些方法,它们是来自OpenJPA:

@Override
public RuntimeException translate(RuntimeException re) {
return PersistenceExceptions.toPersistenceException(re);
}

该方法转换捕获的RuntimeException,这是OpenJPA的UserExceptionSQLException引起的问题,然后在此基础上创建新的PersistenceException并返回它:

/**
* Translate the given general exception.
*/
private static Throwable translateGeneralException(OpenJPAException ke) {
Exception e = new org.apache.openjpa.persistence.PersistenceException
(ke.getMessage(), getNestedThrowables(ke),
getFailedObject(ke), ke.isFatal());
e.setStackTrace(ke.getStackTrace());
return e;
}

正如您所看到的,基于OpenJPAException值(而不是其本身(创建新的org.apache.openjpa.persistence.PersistenceException导致无法检索更低的原因。

OpenJPA 3.1.2版

相关内容

最新更新