gpt4 book ai didi

java - Apache DBCP 连接池与 Hibernate 错误 : Initial SessionFactory creation failed

转载 作者:行者123 更新时间:2023-12-01 12:03:54 25 4
gpt4 key购买 nike

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 池。

最佳答案

您引用的示例适用于旧版本的 Hibernate。它不适用于 Hibernate 4+,因为接口(interface) org.hibernate.connection.ConnectionProvider 不再存在。

我认为新方法是创建一个 org.apache.commons.dbcp.BasicDataSource 实例作为您的数据源。你可以找到一个例子here (向下滚动到“Apache Commons DBCP 示例”)。

也可以通过 Hibernate 配置来实现,如 this answer 所示。 .

关于java - Apache DBCP 连接池与 Hibernate 错误 : Initial SessionFactory creation failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com