Hibernate的Apache DBCP连接池错误:初始SessionFactory创建失败。不知道它有什么问题吗?请查看编号17和158的编号。
> Initial SessionFactory creation failed.java.lang.NullPointerException
> java.lang.NullPointerException at
> ru.user.util.DBCPConnectionProvider.getConnection(DBCPConnectionProvider.java:158)
> at
> org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:279)
> at
> org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124)
> at
> org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
> at
> org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
> at
> org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
> at
> org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
> at
> org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
> at
> ru.user.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
> at ru.user.util.HibernateUtil.<clinit>(HibernateUtil.java:9) at
> ru.user.action.LoginAction.execute(LoginAction.java:43)
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
return configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
在hibernate.cfg.xml
中<property name="hibernate.connection.provider_class">
ru.user.util.DBCPConnectionProvider
</property>
和
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
return configuration.buildSessionFactory(builder.build()); //////// line 17
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public class DBCPConnectionProvider implements ConnectionProvider {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory
.getLogger(DBCPConnectionProvider.class);
private static final String PREFIX = "hibernate.dbcp.";
private BasicDataSource ds;
// Old Environment property for backward-compatibility (property removed in
// Hibernate3)
private static final String DBCP_PS_MAXACTIVE = "hibernate.dbcp.ps.maxActive";
// Property doesn't exists in Hibernate2
private static final String AUTOCOMMIT = "hibernate.connection.autocommit";
public void configure(Properties props) throws HibernateException {
try {
log.debug("Configure DBCPConnectionProvider");
// DBCP properties used to create the BasicDataSource
Properties dbcpProperties = new Properties();
// DriverClass & url
String jdbcDriverClass = props.getProperty(Environment.DRIVER);
String jdbcUrl = props.getProperty(Environment.URL);
dbcpProperties.put("driverClassName", jdbcDriverClass);
dbcpProperties.put("url", jdbcUrl);
// Username / password
String username = props.getProperty(Environment.USER);
String password = props.getProperty(Environment.PASS);
dbcpProperties.put("username", username);
dbcpProperties.put("password", password);
// Isolation level
String isolationLevel = props.getProperty(Environment.ISOLATION);
if ((isolationLevel != null)
&& (isolationLevel.trim().length() > 0)) {
dbcpProperties.put("defaultTransactionIsolation",
isolationLevel);
}
// Turn off autocommit (unless autocommit property is set)
String autocommit = props.getProperty(AUTOCOMMIT);
if ((autocommit != null) && (autocommit.trim().length() > 0)) {
dbcpProperties.put("defaultAutoCommit", autocommit);
} else {
dbcpProperties.put("defaultAutoCommit",
String.valueOf(Boolean.FALSE));
}
// Pool size
String poolSize = props.getProperty(Environment.POOL_SIZE);
if ((poolSize != null) && (poolSize.trim().length() > 0)
&& (Integer.parseInt(poolSize) > 0)) {
dbcpProperties.put("maxActive", poolSize);
}
// Copy all "driver" properties into "connectionProperties"
Properties driverProps = ConnectionProviderInitiator
.getConnectionProperties(props);
if (driverProps.size() > 0) {
StringBuffer connectionProperties = new StringBuffer();
for (Iterator<?> iter = driverProps.entrySet().iterator(); iter
.hasNext();) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
connectionProperties.append(key).append('=').append(value);
if (iter.hasNext()) {
connectionProperties.append(';');
}
}
dbcpProperties.put("connectionProperties",
connectionProperties.toString());
}
// Copy all DBCP properties removing the prefix
for (Iterator<?> iter = props.entrySet().iterator(); iter.hasNext();) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
if (key.startsWith(PREFIX)) {
String property = key.substring(PREFIX.length());
String value = (String) entry.getValue();
dbcpProperties.put(property, value);
}
}
// Backward-compatibility
if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
dbcpProperties.put("poolPreparedStatements",
String.valueOf(Boolean.TRUE));
dbcpProperties.put("maxOpenPreparedStatements",
props.getProperty(DBCP_PS_MAXACTIVE));
}
// Some debug info
if (log.isDebugEnabled()) {
log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
StringWriter sw = new StringWriter();
dbcpProperties.list(new PrintWriter(sw, true));
log.debug(sw.toString());
}
// Let the factory create the pool
ds = (BasicDataSource) BasicDataSourceFactory
.createDataSource(dbcpProperties);
// The BasicDataSource has lazy initialization
// borrowing a connection will start the DataSource
// and make sure it is configured correctly.
Connection conn = ds.getConnection();
conn.close();
// Log pool statistics before continuing.
logStatistics();
} catch (Exception e) {
String message = "Could not create a DBCP pool";
log.error(message, e);
if (ds != null) {
try {
ds.close();
} catch (Exception e2) {
// ignore
}
ds = null;
}
throw new HibernateException(message, e);
}
log.debug("Configure DBCPConnectionProvider complete");
}
public Connection getConnection() throws SQLException {
Connection conn = null;
try {
conn = ds.getConnection(); //////// line 158
} finally {
logStatistics();
}
return conn;
}
public void closeConnection(Connection conn) throws SQLException {
try {
conn.close();
} finally {
logStatistics();
}
}
public void close() throws HibernateException {
log.debug("Close DBCPConnectionProvider");
logStatistics();
try {
if (ds != null) {
ds.close();
ds = null;
} else {
log.warn("Cannot close DBCP pool (not initialized)");
}
} catch (Exception e) {
throw new HibernateException("Could not close DBCP pool", e);
}
log.debug("Close DBCPConnectionProvider complete");
}
protected void logStatistics() {
if (log.isInfoEnabled()) {
// log.info("active: " + ds.getNumActive() + " (max: " +
// ds.getMaxTotal() + ") "
// + "idle: " + ds.getNumIdle() + "(max: " + ds.getMaxIdle() + ")");
}
}
public boolean supportsAggressiveRelease() {
return false;
}
@Override
public boolean isUnwrappableAs(
@SuppressWarnings("rawtypes") Class unwrapType) {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(Class<T> unwrapType) {
// TODO Auto-generated method stub
return null;
}
}
请参阅代码中的注释,其中包含堆栈跟踪中引用的行号。那么机智有什么问题呢?我使用dbcp2池。
答案 0 :(得分:1)
您所指的示例是针对旧版本的Hibernate。它不适用于Hibernate 4+,因为接口org.hibernate.connection.ConnectionProvider
不再存在。
我认为新方法是创建org.apache.commons.dbcp.BasicDataSource
的实例作为您的DataSource。您可以找到示例here(向下滚动到“Apache Commons DBCP示例”)。
也可以通过Hibernate配置来完成,如this answer所示。