This article describes how to extend Hibernate using a custom database connection pool. Share it for your reference, as follows:
In the process of Hibernate, we often encounter this problem: our ready-made products already use our own database connection pool. If we use Hibernate, we must also configure database connection information in the Hibernate configuration. This requires maintaining the database connection information in two places, which feels quite awkward to maintain.
Since we did not join Hibernate at the beginning of the product development, it is not appropriate to let the product directly use Hibernate's connection pool, so we had to let Hibernate use the product's own connection pool. Fortunately, Hibernate has provided an extension interface for the connection pool: ConnectionProvider.
Hibernate itself uses the ConnectionProvider interface to manage database connections. For example, its own C3P0ConnectionProvider, ProxoolConnectionProvider, etc., we write a class that implements the ConnectionProvider interface. In the Hibernate configuration file, it is OK to change the relevant parameters to this class. The relevant code is as follows:
The following code is used to replace the previous database connection information configuration in hibernate.cfg.xml:
<!-- Custom - Connection pool using NMS products--><property name="hibernate.connection.provider_class">com.shine.sourcedesk.jbpm.NmsConnectionProvider</property>
Classes that implement 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;/** * Customize Hibernate connection pool, let Hibernate use the product's ConnectionManager * @author JiangKunpeng * */public class NmsConnectionProvider implements ConnectionProvider{@Overridepublic void close() throws HibernateException {}@Overridepublic void closeConnection(Connection connection) throws SQLException { //Close the connection ConnectionManager.close(connection);}@Overridepublic void configure(Properties properties) throws HibernateException {}@Overridepublic Connection getConnection() throws SQLException { //Use the product's database connection pool to get the connection return ConnectionManager.getConnection();}@Overridepublic boolean supportsAggressiveRelease() { return false;}I hope that the description in this article will be helpful to everyone's Java programming based on the Hibernate framework.