Hibernate Developer Guide1

http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/


Connecting:

  • Stand-alone built-in connection pool

  • javax.sql.DataSource

  • Connection pools, including support for two different third-party opensource JDBC connection pools:

    • c3p0

    • proxool

  • Application-supplied JDBC connections. This is not a recommended approach and exists for legacy reasons

Hibernate obtains JDBC connections as needed though the 

org.hibernate.service.jdbc.connections.spi.ConnectionProvider

 interface which is a service contract. 

Applications may also supply their own 

org.hibernate.service.jdbc.connections.spi.ConnectionProvider implementation 

to define a custom approach for supplying connections to Hibernate (from a different connection pool implementation, for example).


hibernate.properties for a c3p0 connection pool

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

Hibernate's internal connection pooling algorithm is rudimentary, and is provided for development and testing purposes. Use a third-party pool for best performance and stability. To use a third-party pool, replace the hibernate.connection.pool_size property with settings specific to your connection pool of choice. This disables Hibernate's internal connection pool.


1.2.1. c3p0 connection pool

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib/ directory. Hibernate uses its

 org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider

 for connection pooling if you set the hibernate.c3p0.* properties. properties.

Important configuration properties for the c3p0 connection pool

  • hibernate.c3p0.min_size

  • hibernate.c3p0.max_size

  • hibernate.c3p0.timeout

  • hibernate.c3p0.max_statements

1.2.2. Proxool connection pool

Hibernate uses its 

org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider

 for connection pooling if you set the hibernate.proxool.* properties. Unlike c3p0, proxool requires some additional configuration parameters, as described by the Proxool documentation available athttp://proxool.sourceforge.net/configure.html.


hibernate.proxool.xmlConfigure Proxool provider using an XML file (.xml is appended automatically)
hibernate.proxool.propertiesConfigure the Proxool provider using a properties file (.properties is appended automatically)
hibernate.proxool.existing_poolWhether to configure the Proxool provider from an existing pool
hibernate.proxool.pool_aliasProxool pool alias to use. Required.

1.2.3. Obtaining connections from an application server, using JNDI

To use Hibernate inside an application server, configure Hibernate to obtain connections from an application server 

javax.sql.Datasource 

registered in JNDI, by setting at least one of the following properties:


Important Hibernate properties for JNDI datasources

  • hibernate.connection.datasource (required)

  • hibernate.jndi.url

  • hibernate.jndi.class

  • hibernate.connection.username

  • hibernate.connection.password


1.3. Dialects

MySQLorg.hibernate.dialect.MySQLDialect
MySQL with InnoDBorg.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAMorg.hibernate.dialect.MySQLMyISAMDialect
Oracle 10gorg.hibernate.dialect.Oracle10gDialect
Microsoft SQL Server 2005org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008org.hibernate.dialect.SQLServer2008Dialect

1.3.2. Dialect resolution???


1.4. Automatic schema generation with SchemaExport

SchemaExport is a Hibernate utility which generates DDL from your mapping files. 

The generated schema includes referential integrity constraints, primary and foreign keys, 

for entity and collection tables. It also creates tables and sequences for mapped identifier generators.



Chapter 2. Transactions and concurrency control

transaction defination:

  •  physical transaction

    •  logical notion of a transaction as related to a persistence context.

    •  the application notion of a Unit-of-Work, as defined by the archetypal pattern.


2.2. Physical Transactions

Hibernate uses the JDBC API for persistence. In the world of Java there are 2 well defined mechanism for dealing with transactions in JDBC:

 JDBC itself and JTA.

org.hibernate.engine.transaction.spi.TransactionFactory  interface which serves 2 main functions:

  • It allows Hibernate to understand the transaction semantics of the environment. Are we operating in a JTA environment? Is a physical transaction already currently active? etc.

  • It acts as a factory for  org.hibernate.Transaction   instances which are used to allow applications to manage and check the state of transactions. org.hibernate.Transaction is Hibernate's notion of a logical transaction


    JPA has a similar notion in the javax.persistence.EntityTransaction interface.


2.2.1. Physical Transactions - JDBC

JDBC-based transaction management leverages the JDBC defined methods

 java.sql.Connection.commit()and java.sql.Connection.rollback() 

(JDBC does not define an explicit method of beginning a transaction). 


In Hibernate, this approach is represented by the

org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory 

class.


2.2.2. Physical Transactions - JTA

2.2.3. Physical Transactions - CMT

During development of 4.0, most of these classes named here were moved to new packages. To help facilitate upgrading, Hibernate will also recognize the legacy names here for a short period of time.

  • org.hibernate.transaction.JDBCTransactionFactory is mapped toorg.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory

  • org.hibernate.transaction.JTATransactionFactory is mapped toorg.hibernate.engine.transaction.internal.jta.JtaTransactionFactory

  • org.hibernate.transaction.CMTTransactionFactory is mapped toorg.hibernate.engine.transaction.internal.jta.CMTTransactionFactory


Hibernate uses JDBC connections and JTA resources directly, without adding any additional locking behavior.

It is important for you to become familiar with the JDBC, ANSI SQL, and transaction isolation specifics of your database management system.

Hibernate does not lock objects in memory. 

The behavior defined by the isolation level of your database transactions does not change when you use Hibernate. 

The Hibernate org.hibernate.Session acts as a transaction-scoped cache providing repeatable reads 

for lookup by identifier and queries that result in loading entities.


Important

To reduce lock contention in the database, the physical database transaction needs to be as short as possible. Long database transactions prevent your application from scaling to a highly-concurrent load. Do not hold a database transaction open during end-user-level work, but open it after the end-user-level work is finished. This is concept is referred to astransactional write-behind.


2.4. Transactional patterns (and anti-patterns)

2.4.1. Session-per-operation anti-pattern

This is an anti-pattern of opening and closing a Session for each database call in a single thread. 

It is also an anti-pattern in terms of database transactions. 

Group your database calls into a planned sequence. 

In the same way, do not auto-commit after every SQL statement in your application. 

Hibernate disables, or expects the application server to disable, auto-commit mode immediately. 

Database transactions are never optional. 

All communication with a database must be encapsulated by a transaction. 

Avoid auto-commit behavior for reading data, because many small transactions are unlikely to perform better than one clearly-defined unit of work, and are more difficult to maintain and extend.


Note

Using auto-commit does not circumvent database transactions. Instead, when in auto-commit mode, JDBC drivers simply perform each call in an implicit transaction call. It is as if your application called commit after each and every JDBC call.

2.4.2. Session-per-request pattern

This is the most common transaction pattern. 

The term request here relates to the concept of a system that reacts to a series of requests from a client/user. 

Web applications are a prime example of this type of system, though certainly not the only one.

At the beginning of handling such a request, the application opens a Hibernate Session

starts a transaction, performs all data related work, ends the transaction and closes the Session

The crux of the pattern is the one-to-one relationship between the transaction and the Session.


Within this pattern there is a common technique of defining a

current session to simplify the need of passing this Session around to

 all the application components that may need access to it. 

Hibernate provides support for this technique through

the getCurrentSession method of the SessionFactory

The concept of a "current" session has to have a scope that defines the bounds

in which the notion of "current" is valid. 

This is purpose of the org.hibernate.context.spi.CurrentSessionContext contract. 

There are 2 reliable defining scopes:


  • First is a JTA transaction because it allows a callback hook to know when it is ending which gives Hibernate a chance to close the Session and clean up. This is represented by theorg.hibernate.context.internal.JTASessionContext implementation of theorg.hibernate.context.spi.CurrentSessionContext contract. Using this implementation, a Session will be opened the first time getCurrentSession is called within that transaction.

  • Secondly is this application request cycle itself. This is best represented with 

    the org.hibernate.context.internal.ManagedSessionContext 

    implementation of the org.hibernate.context.spi.CurrentSessionContext contract.

    Here an external component is responsible for managing the lifecycle and scoping of a "current" session. At the start of such a scope,ManagedSessionContext's bind method is called passing in the Session. At the end, its unbind method is called.


  • Some common examples of such "external components" include:

    • javax.servlet.Filter implementation

    • AOP interceptor with a pointcut on the service methods

    • A proxy/interception container


Important

The getCurrentSession() method has one downside in a JTA environment. If you use it, after_statement connection release mode is also used by default. Due to a limitation of the JTA specification, Hibernate cannot automatically clean up any unclosed ScrollableResults or Iterator instances returned by scroll() or iterate(). Release the underlying database cursor by calling ScrollableResults.close() or Hibernate.close(Iterator) explicitly from afinally block.

2.4.3. Conversations

The session-per-request pattern is not the only valid way of designing units of work. 

Many business processes require a whole series of interactions with the user that are interleaved with database accesses. In web and enterprise applications, it is not acceptable for a database transaction to span a user interaction. Consider the following example:


Procedure 2.1. An example of a long-running conversation

  1. The first screen of a dialog opens. The data seen by the user is loaded in a particular Session and database transaction. 

    The user is free to modify the objects.

  2. The user uses a UI element to save their work after five minutes of editing. The modifications are made persistent. 

    The user also expects to have exclusive access to the data during the edit session.

Even though we have multiple databases access here, from the point of view of the user, this series of steps represents a single unit of work. There are many ways to implement this in your application.

A first naive implementation might keep the Session and database transaction open 

while the user is editing, 

using database-level locks to prevent other users from modifying the same data 

and to guarantee isolation and atomicity. 

This is an anti-pattern, because lock contention is a bottleneck which will prevent scalability in the future.


Several database transactions are used to implement the conversation. 

In this case, maintaining isolation of business processes becomes the partial responsibility of the application tier. 

A single conversation usually spans several database transactions.

These multiple database accesses can only be atomic as a whole

 if only one of these database transactions (typically the last one) stores the updated data.

 All others only read data. A common way to receive this data is through a wizard-style dialog spanning several request/response cycles. Hibernate includes some features which make this easy to implement.



Hibernate can perform automatic optimistic concurrency control for you. It can automatically detect if a concurrent modification occurred during user think time. Check for this at the end of the conversation.


If you decide to use the session-per-request pattern, all loaded instances will be in the detached state during user think time. Hibernate allows you to reattach the objects and persist the modifications. The pattern is called session-per-request-with-detached-objects. Automatic versioning is used to isolate concurrent modifications.


The Hibernate Session can be disconnected from the underlying JDBC connection after the database transaction has been committed and reconnected when a new client request occurs. This pattern is known as session-per-conversation and makes even reattachment unnecessary. Automatic versioning is used to isolate concurrent modifications and theSession will not be allowed to flush automatically, only explicitly.










































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值