【Hibernate总结系列】hibernate.cfg.xml配置

来源:百度文库 编辑:神马文学网 时间:2024/04/29 13:45:30
Hibernate的描述文件可以是一个properties属性文件,也可以是一个xml文件。下面讲一下Hibernate.cfg.xml的配置。配置格式如下:
1. 配置数据源
在Hibernate.cfg.xml中既可以配置JDBC,也可以配置JNDI。在本小节中讲述数据源如何配置。
hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">




true

net.sf.hibernate.dialect.MySQLDialect

50

30


java:comp/env/jdbc/datasourcename

net.sf.hibernate.connection.DatasourceConnectionProvider
net.sf.hibernate.dialect.SQLServerDialect





2. c3p0连接池
c3p0连接池是Hibernate推荐使用的连接池,若需要使用该连接池时,需要将c3p0的jar包加入到classpath中。c3p0连接池的配置示例如下:
hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



true

net.sf.hibernate.dialect.MySQLDialect

……

……

user

pass
5
20
1800
50





在上述配置中,Hibernate根据配置文件生成连接,再交给c3p0管理。
3. proxool连接池
proxool跟c3p0以及dbcp不一样,它是自己生成连接的,因此连接信息放在proxool配置文件中。使用它时,需要将proxool-0.8.3.jar加入到classespath中。配置举例如下:
hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



true

net.sf.hibernate.dialect.MySQLDialect

pool1
ProxoolConf.xml
net.sf.hibernate.connection.ProxoolConnectionProvider





在hibernate.cfg.xml的同目录下编写proxool的配置文件:ProxoolConf.xml,该文件的配置实例如下:
ProxoolConf.xml




pool1













90000

20

5

100

10


4. dbcp连接池
在hibernate3.0中,已经不再支持dbcp了,hibernate的作者在hibernate.org中,明确指出在实践中发现dbcp有 BUG,在某些种情会产生很多空连接不能释放,所以抛弃了对dbcp的支持。若需要使用dbcp,开发人员还需要将commons-pool-1.2.jar 和commons-dbcp-1.2.1.jar两个jar包加入到classpath中。dbcp与c3p0一样,都是由hibernate建立连接的。
在hibernate2.0中的配置建立如下:
hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



true

net.sf.hibernate.dialect.MySQLDialect

……

……




100
1
60000
10
100
1
60000
10





5. MySql连接配置
在hibernate中,可以配置很多种数据库,例如MySql、Sql Server和Oracle,MySql的配置举例如下:
hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">




true

net.sf.hibernate.dialect.MySQLDialect

50

30

com.mysql.jdbc.Driver

jdbc:mysql://localhost/dbname?characterEncoding=gb2312

root

root





上面使用的驱动类是com.mysql.jdbc.Driver。需要将MySql的连接器jar包(eg. mysql-connector-java-5.0.4-bin.jar)加入到classpath中。
6. Sql Server连接配置
本小节讲述一下Sql Server数据库的hibernate连接设置,在此只给出连接部分的内容,其余部分与2.2.1.5一样,在此不再赘述。内容如下:

net.sourceforge.jtds.jdbc.Driver

jdbc:jtds:sqlserver://localhost:1433;DatabaseName=dbname

sa


上例的驱动类使用的是jtds的驱动类,因此读者需要将jtds的jar包(eg. jtds-1.2.jar)加入到classpath中。
7. Oracle连接配置
本小节讲述一下Sql Server数据库的hibernate连接设置,在此只给出连接部分的内容,其余部分与2.2.1.5一样,在此不再赘述。内容如下:

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@localhost:1521:dbname

test

test