现在的位置: 首页 > 综合 > 正文

17、Hibernate与数据库连接池

2018年02月05日 ⁄ 综合 ⁄ 共 2467字 ⁄ 字号 评论关闭

1、数据库连接池(Connection Pool)。连接池可以看做一个容器,当中存有很多链接可供使用。

Hibernate内置了一个连接池:C3P0,;Apache提供的DBCP:DataBase Connection Pool;连接池对于开发人员来说是透明的。

javax.sql中有一个重要的接口DataSource,

JNDI(Java命名与目录接口)

2、Hibernate的自带连接池配置:在hibernate.cfg.xml中:

<?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="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

		<property name="show_sql">true</property>

		<property name="hibernate.c3p0.min_size">10</property><!-- 连接池中链接的最少数量 -->
		<property name="hibernate.c3p0.max_size">40</property><!-- 连接池中链接的最多数量 -->
		<property name="hibernate.c3p0.timeout">200</property><!-- 连接超时的时间 -->
		<property name="hibernate.c3p0.max_statements">30</property><!-- 这里的statement指的是JDBC中的preparestatement,缓存30 -->
		<property name="hibernate.c3p0.idle_test_period">100</property><!-- 在连接有效之前空闲时间是多少 -->
		
		<!-- 这些信息来自hibernate的环境类Environment -->
		<mapping resource="People.hbm.xml" />
		
		<event type="load">
			<listener class="com.cdtax.event.TestLoadListener"/>
		</event>
		
		<event type="save">
			<listener class="com.cdtax.event.TestSaveListener"/>
		</event>
		<!-- <listener class="com.cdtax.event.TestSaveListener" type="save"/> -->
	</session-factory>

</hibernate-configuration>

红色部分就是Hibernate自带的连接池C3P0的各种配置。

3、Hibernate提供了一种工具,通过JavaBean、HBM或Schema表三者任意一种,就可以生成其他两种。可以通过HBM文件将Java和DB表生成,是在Hibernate的一个工具包中提供了这种功能。这种工具就是Hibernate tools,联合使用Hibernate tools与Ant实现全自动代码生成。

编写build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="hibernate_tools" basedir="." default="dbschema">
	<property file="build.properties"></property>
	<target name="init">
		<path id="lib.path">
			<pathelement path="${bin}"/>
			<fileset dir="${libs}">
				<include name="**.*.jar"/>
			</fileset>
		</path>
	</target>
	
	<taskdef name="hibernatetools" classname="org.hibernate.tool.ant.HibernateToolTask"
			classpathref="lib.path">
	</taskdef>
	
	<target name="dbschema">
		<hibernatetools>
			<configuration configurationfile="${src}/hibernate.cfg.xml"/>
			<hbm2ddl destdir="${dbschema}" export="false" outputfilename="dbschema.sql" />
			<hbm2java jdk5="true" destdir="${src}" />
		</hibernatetools>
	</target>
</project>

这是ant使用的,然后run  as ant,自动生成表和java类。

需要熟悉Ant

抱歉!评论已关闭.