`

Hibernate4 数据库访问

 
阅读更多

1.1数据库连接

  Hibernate可以使您的应用程序连接到数据库它可以通过各种机制进行连接,包括

>Hibernate内置的连接池

>javax.sql.DataSource

>连接池包括两个不同的第三方开源JDBC连接池支持

  • c3p0

  • proxool

>应用程序提供的JDBC连接不是一个推荐做法存在历史遗留问题。

 

*注意:内置的连接不适合用于生产环境。

 

    Hibernate JDBC需要'org.hibernate.service.jdbc.connections.spi.ConnectionProvider'接口支持。应用程序可以实现'org.hibernate.service.jdbc.connections.spi.ConnectionProvider'接口提供自己的实现(例如实现不同的连接池)。

1.1.1 配置
  可以使用properties文件、XML配置文件或者编程方式来配置数据库连接

 

示例1.1 c3p0连接的 hibernate.properties 配置

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

 

示例1.2 数据库连接的 hibernate.cfg.xml 配置

<?xml version='1.0' encoding='utf-8'?>

<hibernate-configuration
        xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
        xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
    <property name="connection.username">sa</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>
    <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

 

 1.1.1.1 编程方式配置

  一个org.hibernate.cfg.Configuration对象中包含了一系列映射文件(*.hbm.xml,将Java类型映射为数据库类型)的集合org.hibernate.cfg.Configuration会建立一个不变的SessoinFactory不同的XML配置文件来加载这些映射您可以以编码方式直接指定映射文件,或者Hibernate帮你寻找映射文件

示例1.3 直接指定映射文件

 

  您可以通过直接实例化来获取一个org.hibernate.cfg.Configuration实例,用它来指定XML映射文件如果映射文件在classpath中,使用方法AddResource()即可

Configuration cfg = new Configuration()
    .addResource("Item.hbm.xml")
    .addResource("Bid.hbm.xml");

 

 示例1.4 Hibernate帮你寻找映射文件

  addClass()方法指示Hibernate搜索CLASSPATH中的映射文件消除硬编码的文件名在下面的例子中,它会去搜索org/hibernate/auction/Item.hbm.xmlorg/hibernate/auction/ Bid.hbm.xml

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);

 示例1.5 指定配置属性

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

 

其他编程方式来配置Hibernate:
>传递一个java.util.Properties到Configuration.setProperties()方法
>使用Java的 -Dproperty = value方式指定,设置为系统属性。

 

1.1.2  获取JDBC连接
    当你在配置完hibernate JDBC的关键属性之后,你可以使用org.hibernate.SessionFactory类的openSession方法来打开session。Session将会根据提供的配置按需获取

JDBC连接。
Hibernate JDBC的关键配置属性:

  • hibernate.connection.driver_class

  • hibernate.connection.url

  • hibernate.connection.username

  • hibernate.connection.password

  • hibernate.connection.pool_size   

    所有可用的Hibernate设置被定义为org.hibernate.cfg.AvailableSettings接口常量和,具体可以查看源代码或者JavaDoc。 

 

1.2. 连接池
    Hibernate的内置连接池其算法是最基本的,主要目的是用于开发和测试。需要使用第三方连接池以获得最佳性能和稳定性。要使用第三方连接池,你需要设置特定的连接池以及
hibernate.connection.pool_size属性。配置第三方连接池之后,内置连接池将失效。

 

1.2.1. c3p0 连接池
    c3p0 是一个开源的JDBC连接池,它放在Hibernate发布包中的lib目录。如果你配置了hibernate.c3p0.*属性,Hibernate会使用

org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider来缓存数据库连接。
c3p0连接池的关键配置属性:

  • hibernate.c3p0.min_size

  • hibernate.c3p0.max_size

  • hibernate.c3p0.timeout

  • hibernate.c3p0.max_statements

1.2.2. Proxool 连接池
    Proxool是另外一个开源连接池,也在Hibernate发布包中的lib目录。如果你配置了hibernate.proxool.* 属性,Hibernate会使用
org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider来缓存数据库连接。和c3p0不同的是,Proxool需要一些额外配置属性,详情可以参考Proxool官方文档:http://proxool.sourceforge.net/configure.html

 

表格1.1 Proxool连接池的关键配置属性

Property Description
hibernate.proxool.xml Configure Proxool provider using an XML file (.xml is appended automatically)
hibernate.proxool.properties Configure the Proxool provider using a properties file (.properties is appended automatically)
hibernate.proxool.existing_pool Whether to configure the Proxool provider from an existing pool
hibernate.proxool.pool_alias Proxool pool alias to use. Required.
 

1.2.3 用JNDI方式,从应用服务器获取数据库连接
    在应用服务器下,Hibernate可以用JNDI方式从注册在服务器上的javax.sql.Datasource中获取数据库连接。你需要配置以下属性中的至少一个属性:
JNDI数据源的关键Hibernate配置属性:

    • hibernate.connection.datasource (required)

    • hibernate.jndi.url

    • hibernate.jndi.class

    • hibernate.connection.username

    • hibernate.connection.password

    从JNDI数据源获取的JDBC连接会自动参与应用服务器中由容器管理的事务(transaction)。

 

1.2.4. 其他数据库连接配置
    你可以通过配置任意以hibernate.connection开头的属性,来传递连接属性。例如,配置hibernate.connection.charSet来指定一个字符集连接属性。你也可以定义你自己的类来

获取JDBC连接,这个类需要实现org.hibernate.service.jdbc.connections.spi.ConnectionProvider 接口,并通过hibernate.connection.provider_class属性来指定它。

 

1.3. 方言
    虽然SQL是相对标准化的,每个数据库供应商使用都是所支持的语法的一个子集。Hibernate通过org.hibernate.dialect.Dialect的不同子类实现来处理这些不同。


表1.2. 支持的数据库方言

    Database             Dialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
Firebird org.hibernate.dialect.FirebirdDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Interbase org.hibernate.dialect.InterbaseDialect
Ingres org.hibernate.dialect.IngresDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle 8i org.hibernate.dialect.Oracle8iDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Pointbase org.hibernate.dialect.PointbaseDialect
PostgreSQL 8.1 org.hibernate.dialect.PostgreSQL81Dialect
PostgreSQL 8.2 and later org.hibernate.dialect.PostgreSQL82Dialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Sybase ASE 15.5 org.hibernate.dialect.SybaseASE15Dialect
Sybase ASE 15.7 org.hibernate.dialect.SybaseASE157Dialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect

 

1.3.1 指定使用方言
    开发人员可以配置hibernate.dialect属性指定数据库方言。

 

1.4 使用SchemaExport工具自动生成数据库Schema
    SchemaExport是一个Hibernate根据映射文件生成DDL的工具。生成的表Schema包含参照完整性约束,主键和外键。
    注意:使用此工具时,您必须通过hibernate.dialet属性指定一个SQL方言,因为DDL在不同的数据库供应商之间是有差异的。
    在Hibernate生成你的Schema前,必须定制你的映射文件。

 

1.4.1 自定义映射文件
    Hibernate提供了多种元素和属性来定制你的映射文件。这些元素和属性如下:
表1.3 映射文件的元素和属性

Name Type of value Description
length number Column length
precision number Decimal precision of column
scale number Decimal scale of column
not-null

true or false

Whether a column is allowed to hold null values
unique

true or false

Whether values in the column must be unique
index string The name of a multi-column index
unique-key string The name of a multi-column unique constraint
foreign-key string The name of the foreign key constraint generated for an association. This applies to <one-to-one>, <many-to-one>, <key>, and <many-to-many> mapping elements. inverse="true" sides are skipped by SchemaExport.
sql-type string Overrides the default column type. This applies to the <column> element only.
default string Default value for the column
check string An SQL check constraint on either a column or atable

 

步骤1.1 自定义Schema
1.设置的长度,精度和小数点的映射元素
很多Hibernate映射元素定义了名为长度,精度和小数点的可选属性。

<property name="zip" length="5"/>
<property name="balance" precision="12" scale="2"/>

 

 

2.设置 not-null, UNIQUE, unique-key 属性
目前,unique-key属性指定的值在生成DDL没有命名的约束,它仅列在映射文件中。

<many-to-one name="bar" column="barId" not-null="true"/>
<element column="serialNumber" type="long" not-null="true" unique="true"/>

<many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/>
<property name="employeeId" unique-key="OrgEmployee"/>

 

 

3.设置 index 和 foreign-key 属性
index 属性用来指定映射的一列或多列的索引名称。您可使用多个列来创建一个索引,它们将拥有相同的索引名称。
foreign-key 属性会覆盖任何生成的外键约束的名称。

<many-to-one name="bar" column="barId" foreign-key="FKFooBar"/>

 


4.设置<column>子元素
很多映射元素有一个或多个<column>子元素。这对于映射类型涉及到多个列时是特别有用的。

<property name="name" type="my.customtypes.Name"/>
    <column name="last" not-null="true" index="bar_idx" length="30"/>
    <column name="first" not-null="true" index="bar_idx" length="20"/>
    <column name="initial"/>
</property>

 

 

5.设置 default 属性
default属性代表一列的默认值。保存前被映射的类的新实例的相应属性会被赋予该值。

<property name="credits" type="integer" insert="false">
    <column name="credits" default="10"/>
</property>
<version name="version" type="integer" insert="false">
    <column name="version" default="0"/>
</property>

 

6.设置 sql-type 属性
使用sql-type属性来覆盖映射到SQL数据类型的默认Hibernate类型。

<property name="balance" type="float">
    <column name="balance" sql-type="decimal(13,3)"/>
</property>

 

7.设置 check 属性
使用check属性指定一个约束检查。

<property name="foo" type="integer">
  <column name="foo" check="foo > 10"/>
</property>
<class name="Foo" table="foos" check="bar < 100.0">
  ...
  <property name="bar" type="float"/>
</class>

 

8.添加 <comment> 元素
使用<comment>元素可以为生成的Schema指定注释。

<class name="Customer" table="CurCust">
  <comment>Current customers only</comment>
  ...
</class>

 

1.4.2 运行SchemaExport工具
    SchemaExport工具把DDL脚本写到标准输出,执行DDL语句,或两者兼而有之。


示例1.7 SchemaExport工具语法

java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files

 

表1.4 SchemaExport工具选项

Option Description
--quiet do not output the script to standard output
--drop only drop the tables
--create only create the tables
--text do not export to the database

--output=my_schema.ddl

output the ddl script to a file

--naming=eg.MyNamingStrategy

select a NamingStrategy

--config=hibernate.cfg.xml

read Hibernate configuration from an XML file

--properties=hibernate.properties

read database properties from a file
--format format the generated SQL nicely in the script

--delimiter=;

set an end-of-line delimiter for the script

 

示例1.8 嵌入SchemaExport工具到您的应用程序

Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);

 

 

 

 [原文 http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch01.html ]

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics