Extend Hibernate's method of using custom database connection pools

  • 2020-05-07 19:43:58
  • OfStack

This article illustrates how to extend Hibernate to use a custom database connection pool. Share with you for your reference, as follows:

In the process of Hibernate, we often encounter the problem that our off-the-shelf products already use their own database connection pool, and if we use Hibernate at the same time, we have to configure the database connection information in the Hibernate configuration, so we need to maintain the database connection information in two places, which is quite awkward to maintain.

Since we did not join Hibernate at the beginning of the product development, it is not appropriate for the product to directly use Hibernate's connection pool, so we have to let Hibernate use the product's own connection pool. Fortunately, Hibernate has provided an extension interface for the connection pool: ConnectionProvider.

Hibernate itself manages database connections through the ConnectionProvider interface. For example, its own C3P0ConnectionProvider, ProxoolConnectionProvider, we wrote a class to implement ConnectionProvider interface, in the configuration file of Hibernate to change the relevant parameters to this class for OK, the relevant code is as follows:

hibernate.cfg.xml replaces the previous database connection information configuration with the following code:


<!--  The custom - use NMS Product connection pool  -->
<property name="hibernate.connection.provider_class">
com.shine.sourcedesk.jbpm.NmsConnectionProvider
</property>

Class implementing ConnectionManager interface:


package com.shine.sourcedesk.jbpm;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;
import com.shine.framework.jdbc.ConnectionManager;
/**
 *  The custom Hibernate The connection pool , let Hibernate product-using ConnectionManager
 * @author JiangKunpeng
 *
 */
public class NmsConnectionProvider implements ConnectionProvider{
@Override
public void close() throws HibernateException {
}
@Override
public void closeConnection(Connection connection) throws SQLException {
    // Close the connection 
    ConnectionManager.close(connection);
}
@Override
public void configure(Properties properties) throws HibernateException {
}
@Override
public Connection getConnection() throws SQLException {
    // Get the connection using the product's database connection pool 
    return ConnectionManager.getConnection();
}
@Override
public boolean supportsAggressiveRelease() {
    return false;
}

I hope this article is helpful for you to design Java program based on Hibernate framework.


Related articles: