Hibernateでc3p0を使用する
1. 概要
データベース接続を確立するにはかなりの費用がかかります。 データベースconnection poolingは、この支出を削減するための確立された方法です。
このチュートリアルでは、Hibernateでc3p0を使用して接続をプールする方法について説明します。
2. c3p0とは何ですか?
c3p0 isa Java library that provides a convenient way for managing database connections。
つまり、接続のプールを作成することでこれを実現します。 また、使用後のStatementsとResultSetsのクリーンアップも効果的に処理します。 このクリーンアップは、リソースの使用が最適化され、回避可能なデッドロックが発生しないようにするために必要です。
This library integrates seamlessly with various traditional JDBC drivers.さらに、DriverManagerベースのJDBCドライバーを新しいjavax.sql.DataSource schemeに適合させるためのレイヤーを提供します。
また、HibernateはJDBCを介したデータベースへの接続をサポートしているため、it’s simple to use Hibernate and c3p0 together.
3. Hibernateを使用したc3p0の構成
次に、データベース接続マネージャーとしてc3p0を使用するように既存のHibernateアプリケーションを構成する方法を見てみましょう。
3.1. Mavenの依存関係
まず、最初にhibernate-c3p0Maven依存関係を追加する必要があります。
org.hibernate
hibernate-c3p0
5.3.6.Final
Hibernate 5では、c3p0を有効にするには上記の依存関係を追加するだけで十分です。 This is true as long as no other JDBC connection pool manager is specified.
したがって、依存関係を追加した後、アプリケーションを実行してログを確認できます。
Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
Initializing c3p0 pool... [email protected] [ ... default settings ... ]
別のJDBC接続プールマネージャーが使用されている場合、c3p0を使用するようにアプリケーションを強制できます。 プロパティファイルでprovider_classをC3P0ConnectionProviderに設定する必要があります。
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
3.2. 接続プールのプロパティ
最終的には、デフォルトの構成をオーバーライドする必要があります。 hibernate.cfg.xmlファイルにカスタムプロパティを追加できます。
5
20
5
1800
同様に、hibernate.propertiesファイルには同じ設定を含めることができます。
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
min_sizeプロパティは、任意の時点で維持する必要のある接続の最小数を指定します。 By default, it will maintain at least three connections。 この設定は、プールの初期サイズも定義します。
max_sizeプロパティは、任意の時点で維持できる接続の最大数を指定します。 By default, it will keep a maximum of 15 connections。
acquire_incrementプロパティは、プールで使用可能な接続が不足した場合に取得を試行する接続の数を指定します。 デフォルトでは、3つの新しい接続を取得しようとします。
timeoutプロパティは、未使用の接続が破棄されるまでに保持される秒数を指定します。 By default, connections will never expire from the pool.
ログを再度確認することで、新しいプール設定を確認できます。
Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
Initializing c3p0 pool... [email protected] [ ... new settings ... ]
これらは、基本的な接続プールプロパティです。 さらに、他の構成プロパティはofficial guideにあります。