Hibernate.orgCommunity Documentation

Capítulo 2. Arquitetura

2.1. Visão Geral
2.1.1. Minimal architecture
2.1.2. Comprehensive architecture
2.1.3. Basic APIs
2.2. Integração JMX
2.3. Sessões Contextuais

O diagrama abaixo fornece uma visão de altíssimo nível da arquitetura do Hibernate:

Unfortunately we cannot provide a detailed view of all possible runtime architectures. Hibernate is sufficiently flexible to be used in a number of ways in many, many architectures. We will, however, illustrate 2 specifically since they are extremes.

Here are quick discussions about some of the API objects depicted in the preceding diagrams (you will see them again in more detail in later chapters).

SessionFactory (org.hibernate.SessionFactory)

A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.

Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application's persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier.

Objetos persistentes e coleções

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation). Capítulo 11, Trabalhando com objetos discusses transient, persistent and detached object states.

Objetos e coleções desanexados e transientes

Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session. Capítulo 11, Trabalhando com objetos discusses transient, persistent and detached object states.

Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional.

ConnectionProvider (org.hibernate.connection.ConnectionProvider)

(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

TransactionFactory (org.hibernate.TransactionFactory)

(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

Extension Interfaces

O Hibernate oferece várias opções de interfaces estendidas que você pode implementar para customizar sua camada persistente. Veja a documentação da API para maiores detalhes.

JMX é o padrão do J2EE para manipulação de componentes Java. O Hibernate pode ser manipulado por um serviço JMX padrão. Nós fornecemos uma implementação do MBean na distribuição: org.hibernate.jmx.HibernateService.

Another feature available as a JMX service is runtime Hibernate statistics. See Seção 3.4.6, “Estatísticas do Hibernate” for more information.

A maioria das aplicações que usa o Hibernate necessita de algum tipo de sessão "contextual", onde uma sessão dada é na verdade um escopo de um contexto. Entretanto, através de aplicações, a definição sobre um contexto é geralmente diferente; e contextos diferentes definem escopos diferentes. Aplicações usando versões anteriores ao Hibernate 3.0 tendem a utilizar tanto sessões contextuais baseadas em ThreadLocal, classes utilitárias como HibernateUtil, ou utilizar frameworks de terceiros (como Spring ou Pico) que provê sessões contextuais baseadas em proxy.

A partir da versão 3.0.1, o Hibernate adicionou o método SessionFactory.getCurrentSession(). Inicialmente, este considerou o uso de transações JTA, onde a transação JTA definia tanto o escopo quanto o contexto de uma sessão atual. Dada a maturidade de diversas implementações autônomas disponíveis do JTA TransactionManager, a maioria (se não todos) dos aplicativos deveria utilizar o gerenciador de transações JTA sendo ou não instalados dentro de um recipiente J2EE. Baseado neste recurso, você deve sempre utilizar sessões contextuais baseadas em JTA.

Entretanto, a partir da versão 3.1, o processo por trás do método SessionFactory.getCurrentSession() é agora plugável. Com isso, uma nova interface (org.hibernate.context.CurrentSessionContext) e um novo parâmetro de configuração (hibernate.current_session_context_class) foram adicionados para possibilitar a compatibilidade do contexto e do escopo na definição de sessões correntes.

Consulte no Javadocs sobre a interface org.hibernate.context.CurrentSessionContext para uma discussão detalhada. Ela define um método único, currentSession(), pelo qual a implementação é responsável por rastrear a sessão contextual atual. Fora da caixa, o Hibernate surge com três implementações dessa interface:

The first two implementations provide a "one session - one database transaction" programming model. This is also known and used as session-per-request. The beginning and end of a Hibernate session is defined by the duration of a database transaction. If you use programmatic transaction demarcation in plain JSE without JTA, you are advised to use the Hibernate Transaction API to hide the underlying transaction system from your code. If you use JTA, you can utilize the JTA interfaces to demarcate transactions. If you execute in an EJB container that supports CMT, transaction boundaries are defined declaratively and you do not need any transaction or session demarcation operations in your code. Refer to Capítulo 13, Transações e Concorrência for more information and code examples.

O parâmetro de configuração hibernate.current_session_context_class define qual implementação org.hibernate.context.CurrentSessionContext deve ser usada. Note que para compatibilidade anterior, se este parâmetro de configuração não for determinado mas um org.hibernate.transaction.TransactionManagerLookup for configurado, Hibernate usará o org.hibernate.context.JTASessionContext. Tipicamente, o valor deste parâmetro nomearia apenas a classe de implementação para usar; para as três implementações fora da caixa, entretanto, há dois pequenos nomes correspondentes, "jta", "thread", e "managed".