由于之前自己学习时,都是使用的Mybatis进行的数据库相关操作。这次刚进公司需要去将tomcat里面的数据连接配置转移到Hibernate上,正好学习到了Hibernate配置文件的书写。
书写顺序基本就是以下三步:
- 配置所连接数据库的基本信息
- 配置数据库连接池的基本信息
- 配置Hibernate如二级缓存、调试、log等参数
0.基本框架
<?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">
<hibernate-configuration>
<session-factory>
</session-factory>
</hibernate-configuration>
1.配置数据库基本信息
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://***.***.***.***:3306/***</property>
<property name="hibernate.connection.username">***</property>
<property name="hibernate.connection.password"> ***</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
2.配置数据库连接池的基本信息
<!-- c3p0在我们使用的Hibernate版本中自带,不用下载,直接使用 -->
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<!--下面这句很重要,断线重联就是这个-->
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
3.配置Hibernate参数
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Hibernate二级缓存配置 Bigin -->
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- Hibernate3的用法 : <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> -->
<!-- Hibernate4的用法 如下: -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- Hibernate二级缓存配置 end -->
<!--从当前线程中获取session : H4配置会报错 -->
<!-- <property name="hibernate.current_session_context_class">thread</property> -->
<property name="hibernate.auto-import">false</property>
<!-- 数据库连接释放模式 -->
<property name="hibernate.connection.release_mode">after_transaction</property>
<!-- 调试时使用 -->
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">false</property>
<!-- 统计缓存信息 -->
<property name="hibernate.generate_statistics">true</property>