在没有配置数据库连接池时候,hibernate默认调用自己的连接池:
2010-06-11 14:40:43,843 [http-8080-1] INFO [org.hibernate.connection.DriverManagerConnectionProvider] - Using Hibernate built-in connection pool (not for production use!)
2010-06-11 14:40:43,843 [http-8080-1] INFO [org.hibernate.connection.DriverManagerConnectionProvider] - Hibernate connection pool size: 20
2010-06-11 14:40:43,843 [http-8080-1] INFO [org.hibernate.connection.DriverManagerConnectionProvider] - autocommit mode: false
2010-06-11 14:40:43,859 [http-8080-1] INFO [org.hibernate.connection.DriverManagerConnectionProvider] - using driver: com.mysql.jdbc.Driver at URL:
jdbc:mysql://localhost:3306/test
2010-06-11 14:40:43,859 [http-8080-1] INFO [org.hibernate.connection.DriverManagerConnectionProvider] - connection properties: {user=root, password=****}
配置c3p0连接池,是hibernate,调用如下:
2010-06-11 14:42:42,250 [http-8080-1] INFO [org.hibernate.connection.C3P0ConnectionProvider] - C3P0 using driver: com.mysql.jdbc.Driver at URL:
jdbc:mysql://localhost:3306/test
2010-06-11 14:42:42,250 [http-8080-1] INFO [org.hibernate.connection.C3P0ConnectionProvider] - Connection properties: {user=root, password=****}
2010-06-11 14:42:42,250 [http-8080-1] INFO [org.hibernate.connection.C3P0ConnectionProvider] - autocommit mode: false
2010-06-11 14:42:42,328 [http-8080-1] INFO [com.mchange.v2.log.MLog] - MLog clients using log4j logging.
2010-06-11 14:42:42,750 [http-8080-1] INFO [com.mchange.v2.c3p0.C3P0Registry] - Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
2010-06-11 14:42:43,109 [http-8080-1] INFO [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] - Initializing c3p0 pool...
com.mchange.v2.c3p0.PoolBackedDataSource@6fa51ffa [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@6c4b4479 [ acquireIncrement
-> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false,
factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge14n89ah1akkd0agla|410541, idleConnectionTestPeriod -> 100, initialPoolSize -> 1,
maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 100, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 1, maxStatements -> 0,
maxStatementsPerConnection -> 0, minPoolSize -> 1, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@b9f77019 [ description -> null, driverClass -> null,
factoryClassLocation -> null, identityToken -> 1hge14n89ah1akkd0agla|121cbdb, jdbcUrl -> jdbc:mysql://localhost:3306/test, properties -> {user=******, password=******} ],
preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0,
usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1hge14n89ah1akkd0agla|224002,
numHelperThreads -> 3 ]
具体的配置如下:
在hibernate对应的属性文件配置:
#c3p0 pool settings
hibernate.c3p0.min_size=1
hibernate.c3p0.max_size=1
hibernate.c3p0.timeout=100
hibernate.c3p0.max_statement=3
hibernate.c3p0.idle_test_period=100
或者,在hibernatexml文件里配置
C3P0连接池详细配置与实现
<c3p0-config>
<default-config>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement">3</property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts">30</property>
<!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
<property name="acquireRetryDelay">1000</property>
<!--连接关闭时默认将所有未提交的操作回滚。Default: false -->
<property name="autoCommitOnClose">false</property>
<!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么
属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试
使用。Default: null-->
<property name="automaticTestTable">Test</property>
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
<property name="breakAfterAcquireFailure">false</property>
<!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出
SQLException,如设为0则无限期等待。单位毫秒。Default: 0 -->
<property name="checkoutTimeout">100</property>
<!--通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。
Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester-->
<property name="connectionTesterClassName"></property>
<!--指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可
Default: null-->
<property name="factoryClassLocation">null</property>
<!--Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs.
(文档原文)作者强烈建议不使用的一个属性-->
<property name="forceIgnoreUnresolvedTransactions">false</property>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod">60</property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize">3</property>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">60</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize">15</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements">100</property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection"></property>
<!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能
通过多线程实现多个操作同时被执行。Default: 3-->
<property name="numHelperThreads">3</property>
<!--当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0
的数据源时。Default: null-->
<property name="overrideDefaultUser">root</property>
<!--与overrideDefaultUser参数对应使用的一个参数。Default: null-->
<property name="overrideDefaultPassword">password</property>
<!--密码。Default: null-->
<property name="password"></property>
<!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
测试的表必须在初始数据源的时候就存在。Default: null-->
<property name="preferredTestQuery">select id from test where id=1</property>
<!--用户修改系统配置参数执行前最多等待300秒。Default: 300 -->
<property name="propertyCycle">300</property>
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout">false</property>
<!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false -->
<property name="testConnectionOnCheckin">true</property>
<!--用户名。Default: null-->
<property name="user">root</property>
<!--早期的c3p0版本对JDBC接口采用动态反射代理。在早期版本用途广泛的情况下这个参数
允许用户恢复到动态反射代理以解决不稳定的故障。最新的非反射代理更快并且已经开始
广泛的被使用,所以这个参数未必有用。现在原先的动态反射与新的非反射代理同时受到
支持,但今后可能的版本可能不支持动态反射代理。Default: false-->
<property name="usesTraditionalReflectiveProxies">false</property>
<property name="automaticTestTable">con_test</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">25</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">0</property>
<user-overrides user="swaldman">
</user-overrides>
</default-config>
<named-config name="dumbTestConfig">
<property name="maxStatements">200</property>
<user-overrides user="poop">
<property name="maxStatements">300</property>
</user-overrides>
</named-config>
</c3p0-config>
c3p0的实现
<!--
全局使用c3p0
1. server.xml中GlobalNamingResources
2. context.xml中ResourceLink
3. web.xml
-->
全局使用c3p0
1. server.xml中GlobalNamingResources
<Resource auth="Container"
description="DB Connection"
driverClass="org.gjt.mm.mysql.Driver"
maxPoolSize="10"
minPoolSize="2"
acquireIncrement="2"
name="jdbc/mysql1"
user="root"
password="xxxxxx"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/noticemanager?characterEncoding=UTF-8&useUnicode=TRUE&autoReconnect=true" />
2. context.xml中ResourceLink
<ResourceLink name="jdbc/mysql1" global="jdbc/mysql1" type="javax.sql.DataSource"/>
3. web.xml
<resource-ref>
<description>Tomcat Datasource</description>
<res-ref-name>jdbc/mysql1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4.Hibernate中的配置
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">100</property>
<property name="c3p0.time_out">1800</property>
<property name="c3p0.max_statement">100</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="jndi.url">
jdbc:mysql://localhost:3306/noticemanager
</property>
<!-- <property name="jndi.class">
org.gjt.mm.mysql.Driver
</property> -->
<property name="connection.datasource">
java:comp/env/jdbc/mysql1
</property>
<property name="connection.username">root</property>
<property name="connection.password">xxxxxxxxx</property>
<property name="hibernate.show_sql">true</property>
<!-- <property name="hibernate.use_outer_join">true</property> -->
<mapping resource="com/dpoo/pojo/Notice.hbm.xml" />
</session-factory>
</hibernate-configuration>
JDBC实现:与DateSource相同
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql1");
conn = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/allenzue/archive/2008/12/19/3550342.aspx
具体的hibernate默认配置细节,可以查看org.hibernate.cfg.Environment 这里面对一些属性文件对应的key都有说明,不用死记硬背滴
==============我把一些拷贝出来,可以参考下=====================================
public static final String VERSION = "3.1 rc3";
/**
* <tt>ConnectionProvider</tt> implementor to use when obtaining connections
*/
public static final String CONNECTION_PROVIDER ="hibernate.connection.provider_class";
/**
* JDBC driver class
*/
public static final String DRIVER ="hibernate.connection.driver_class";
/**
* JDBC transaction isolation level
*/
public static final String ISOLATION ="hibernate.connection.isolation";
/**
* JDBC URL
*/
public static final String URL ="hibernate.connection.url";
/**
* JDBC user
*/
public static final String USER ="hibernate.connection.username";
/**
* JDBC password
*/
public static final String PASS ="hibernate.connection.password";
/**
* JDBC autocommit mode
*/
public static final String AUTOCOMMIT ="hibernate.connection.autocommit";
/**
* Maximum number of inactive connections for Hibernate's connection pool
*/
public static final String POOL_SIZE ="hibernate.connection.pool_size";
/**
* <tt>java.sql.Datasource</tt> JNDI name
*/
public static final String DATASOURCE ="hibernate.connection.datasource";
/**
* prefix for arbitrary JDBC connection properties
*/
public static final String CONNECTION_PREFIX = "hibernate.connection";
/**
* JNDI initial context class, <tt>Context.INITIAL_CONTEXT_FACTORY</tt>
*/
public static final String JNDI_CLASS ="hibernate.jndi.class";
/**
* JNDI provider URL, <tt>Context.PROVIDER_URL</tt>
*/
public static final String JNDI_URL ="hibernate.jndi.url";
/**
* prefix for arbitrary JNDI <tt>InitialContext</tt> properties
*/
public static final String JNDI_PREFIX = "hibernate.jndi";
/**
* JNDI name to bind to <tt>SessionFactory</tt>
*/
public static final String SESSION_FACTORY_NAME = "hibernate.session_factory_name";
/**
* Hibernate SQL <tt>Dialect</tt> class
*/
public static final String DIALECT ="hibernate.dialect";
/**
* A default database schema (owner) name to use for unqualified tablenames
*/
public static final String DEFAULT_SCHEMA = "hibernate.default_schema";
/**
* A default database catalog name to use for unqualified tablenames
*/
public static final String DEFAULT_CATALOG = "hibernate.default_catalog";
/**
* Enable logging of generated SQL to the console
*/
public static final String SHOW_SQL ="hibernate.show_sql";
/**
* Enable formatting of SQL logged to the console
*/
public static final String FORMAT_SQL ="hibernate.format_sql";
/**
* Add comments to the generated SQL
*/
public static final String USE_SQL_COMMENTS ="hibernate.use_sql_comments";
/**
* Maximum depth of outer join fetching
*/
public static final String MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
/**
* The default batch size for batch fetching
*/
public static final String DEFAULT_BATCH_FETCH_SIZE = "hibernate.default_batch_fetch_size";
/**
* Use <tt>java.io</tt> streams to read / write binary data from / to JDBC
*/
public static final String USE_STREAMS_FOR_BINARY = "hibernate.jdbc.use_streams_for_binary";
/**
* Use JDBC scrollable <tt>ResultSet</tt>s. This property is only necessary when there is
* no <tt>ConnectionProvider</tt>, ie. the user is supplying JDBC connections.
*/
public static final String USE_SCROLLABLE_RESULTSET = "hibernate.jdbc.use_scrollable_resultset";
/**
* Tells the JDBC driver to attempt to retrieve row Id with the JDBC 3.0 PreparedStatement.getGeneratedKeys()
* method. In general, performance will be better if this property is set to true and the underlying
* JDBC driver supports getGeneratedKeys().
*/
public static final String USE_GET_GENERATED_KEYS = "hibernate.jdbc.use_get_generated_keys";
/**
* Gives the JDBC driver a hint as to the number of rows that should be fetched from the database
* when more rows are needed. If <tt>0</tt>, JDBC driver default settings will be used.
*/
public static final String STATEMENT_FETCH_SIZE = "hibernate.jdbc.fetch_size";
/**
* Maximum JDBC batch size. A nonzero value enables batch updates.
*/
public static final String STATEMENT_BATCH_SIZE = "hibernate.jdbc.batch_size";
/**
* Select a custom batcher.
*/
public static final String BATCH_STRATEGY = "hibernate.jdbc.factory_class";
/**
* Should versioned data be included in batching?
*/
public static final String BATCH_VERSIONED_DATA = "hibernate.jdbc.batch_versioned_data";
/**
* An XSLT resource used to generate "custom" XML
*/
public static final String OUTPUT_STYLESHEET ="hibernate.xml.output_stylesheet";
=======================这里是c3p0的一些配置,都有可以看下=========================
/**
* Maximum size of C3P0 connection pool
*/
public static final String C3P0_MAX_SIZE = "hibernate.c3p0.max_size";
/**
* Minimum size of C3P0 connection pool
*/
public static final String C3P0_MIN_SIZE = "hibernate.c3p0.min_size";
/**
* Maximum idle time for C3P0 connection pool
*/
public static final String C3P0_TIMEOUT = "hibernate.c3p0.timeout";
/**
* Maximum size of C3P0 statement cache
*/
public static final String C3P0_MAX_STATEMENTS = "hibernate.c3p0.max_statements";
/**
* Number of connections acquired when pool is exhausted
*/
public static final String C3P0_ACQUIRE_INCREMENT = "hibernate.c3p0.acquire_increment";
/**
* Idle time before a C3P0 pooled connection is validated
*/
public static final String C3P0_IDLE_TEST_PERIOD = "hibernate.c3p0.idle_test_period";
/**
* Proxool/Hibernate property prefix
*/
public static final String PROXOOL_PREFIX = "hibernate.proxool";
/**
* Proxool property to configure the Proxool Provider using an XML (<tt>/path/to/file.xml</tt>)
*/
public static final String PROXOOL_XML = "hibernate.proxool.xml";
/**
* Proxool property to configure the Proxool Provider using a properties file (<tt>/path/to/proxool.properties</tt>)
*/
public static final String PROXOOL_PROPERTIES = "hibernate.proxool.properties";
/**
* Proxool property to configure the Proxool Provider from an already existing pool (<tt>true</tt> / <tt>false</tt>)
*/
public static final String PROXOOL_EXISTING_POOL = "hibernate.proxool.existing_pool";
/**
* Proxool property with the Proxool pool alias to use
* (Required for <tt>PROXOOL_EXISTING_POOL</tt>, <tt>PROXOOL_PROPERTIES</tt>, or
* <tt>PROXOOL_XML</tt>)
*/
public static final String PROXOOL_POOL_ALIAS = "hibernate.proxool.pool_alias";
/**
* Enable automatic session close at end of transaction
*/
public static final String AUTO_CLOSE_SESSION = "hibernate.transaction.auto_close_session";
/**
* Enable automatic flush during the JTA <tt>beforeCompletion()</tt> callback
*/
public static final String FLUSH_BEFORE_COMPLETION = "hibernate.transaction.flush_before_completion";
/**
* Specifies how Hibernate should release JDBC connections.
*/
public static final String RELEASE_CONNECTIONS = "hibernate.connection.release_mode";
/**
* Context scoping impl for {@link org.hibernate.SessionFactory#getCurrentSession()} processing.
*/
public static final String CURRENT_SESSION_CONTEXT_CLASS = "hibernate.current_session_context_class";
/**
* <tt>TransactionFactory</tt> implementor to use for creating <tt>Transaction</tt>s
*/
public static final String TRANSACTION_STRATEGY = "hibernate.transaction.factory_class";
/**
* <tt>TransactionManagerLookup</tt> implementor to use for obtaining the <tt>TransactionManager</tt>
*/
public static final String TRANSACTION_MANAGER_STRATEGY = "hibernate.transaction.manager_lookup_class";
/**
* JNDI name of JTA <tt>UserTransaction</tt> object
*/
public static final String USER_TRANSACTION = "jta.UserTransaction";
/**
* The <tt>CacheProvider</tt> implementation class
*/
public static final String CACHE_PROVIDER = "hibernate.cache.provider_class";
/**
* The <tt>CacheProvider</tt> JNDI namespace, if pre-bound to JNDI.
*/
public static final String CACHE_NAMESPACE = "hibernate.cache.jndi";
/**
* Enable the query cache (disabled by default)
*/
public static final String USE_QUERY_CACHE = "hibernate.cache.use_query_cache";
/**
* The <tt>QueryCacheFactory</tt> implementation class.
*/
public static final String QUERY_CACHE_FACTORY = "hibernate.cache.query_cache_factory";
/**
* Enable the second-level cache (enabled by default)
*/
public static final String USE_SECOND_LEVEL_CACHE = "hibernate.cache.use_second_level_cache";
/**
* Optimize the cache for mimimal puts instead of minimal gets
*/
public static final String USE_MINIMAL_PUTS = "hibernate.cache.use_minimal_puts";
/**
* The <tt>CacheProvider</tt> region name prefix
*/
public static final String CACHE_REGION_PREFIX = "hibernate.cache.region_prefix";
/**
* Enable use of structured second-level cache entries
*/
public static final String USE_STRUCTURED_CACHE = "hibernate.cache.use_structured_entries";
/**
* Enable statistics collection
*/
public static final String GENERATE_STATISTICS = "hibernate.generate_statistics";
public static final String USE_IDENTIFIER_ROLLBACK = "hibernate.use_identifier_rollback";
/**
* Use CGLIB <tt>MetaClass</tt> to optimize property access
*/
public static final String USE_REFLECTION_OPTIMIZER = "hibernate.cglib.use_reflection_optimizer";
/**
* The classname of the HQL query parser factory
*/
public static final String QUERY_TRANSLATOR = "hibernate.query.factory_class";
/**
* A comma-seperated list of token substitutions to use when translating a Hibernate
* query to SQL
*/
public static final String QUERY_SUBSTITUTIONS = "hibernate.query.substitutions";
/**
* Auto export/update schema using hbm2ddl tool. Valid values are <tt>update</tt>,
* <tt>create</tt>, <tt>create-drop</tt> and <tt>validate</tt>.
*/
public static final String HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
/**
* The {@link org.hibernate.exception.SQLExceptionConverter} to use for converting SQLExceptions
* to Hibernate's JDBCException hierarchy. The default is to use the configured
* {@link org.hibernate.dialect.Dialect}'s preferred SQLExceptionConverter.
*/
public static final String SQL_EXCEPTION_CONVERTER = "hibernate.jdbc.sql_exception_converter";
/**
* Enable wrapping of JDBC result sets in order to speed up column name lookups for
* broken JDBC drivers
*/
public static final String WRAP_RESULT_SETS = "hibernate.jdbc.wrap_result_sets";
/**
* Enable ordering of update statements by primary key value
*/
public static final String ORDER_UPDATES = "hibernate.order_updates";
/**
* The EntityMode in which set the Session opened from the SessionFactory.
*/
public static final String DEFAULT_ENTITY_MODE = "hibernate.default_entity_mode";