Hibernate Core Reference Manual学习笔记——Chapter 2. Architecture

Hibernate Core Reference Manual

Chapter 2. Architecture


Table of Contents
2.1. Overview
2.1.1. Minimal architecture
2.1.2. Comprehensive architecture
2.1.3. Basic APIs
2.2. JMX Integration
2.3. Contextual sessions


2.1. Overview
站在很高的层次看Hibernate,它是下面这个样子:


 
由于Hibernate架构十分的灵活,所以我们不可能提供所有可能的运行时架构。这里只介绍介绍两种特殊情况:
2.1.1. Minimal architecture
最简架构:应用程序自己管理它的JDBC连接,并把这些连接提供给Hibernate。同时,应用程序自己管理transaction。这种方式使用了Hibernate API的一个最小子集。


 
2.1.2. Comprehensive architecture
"comprehensive"架构使应用程序从底层的JDBC和JTA API抽象出来,并让Hibernate来管理这些细节。



2.1.3. Basic APIs

 

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 oforg.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 fororg.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.

Persistent objects and collections

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). Chapter 11, Working with objects discusses transient, persistent and detached object states.

Transient and detached objects and collections

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. Chapter 11, Working with objects 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

Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.



2.2. JMX Integration
JMX is the J2EE standard for the management of Java components. Hibernate can be managed via a JMX standard service. AN MBean implementation is provided in the distribution: org.hibernate.jmx.HibernateService.


2.3. Contextual sessions
大多数使用Hibernate的应用程序都需要某种形式的"contextual" session,在这个给定的context的scope中,session都是有效地。然而,通常情况下,应用程序对 “由什么组成context”的定义是不同的;由于对current的理解不同,导致不同的context定义不同的scope。


使用Hibernate 3.0(及以前)的应用程序通常会利用ThreadLocal-based contextual sessions和辅助类HibernateUtil,或者是利用第三方的框架,例如Spring和Pico,他们可以提供proxy/interception-based contextual sessions.


从Hibernate 3.0.1开始,Hibernate添加了 SessionFactory.getCurrentSession()方法。起初,这个方法假定使用JTA transactions,而JTA transaction定义当前session的scope和context。考虑到很多独立的JTA TransactionManager实现都很成熟,在绝大多数情况下,应用程序应该使用JTA transaction management。不论应用程序是否部署到J2EE容器中去。基于此,the JTA-based contextual sessions are all you need to use.


但是到了Hibernate 3.1,SessionFactory.getCurrentSession()底层的处理变成了可插拔的。为了实现这一目标,一个新的接口org.hibernate.context.spi.CurrentSessionContext和一个新的配置参数 hibernate.current_session_context_class被添加进来。这就允许你以可插拔的方式配置当前session的scope和context。

查看 org.hibernate.context.spi.CurrentSessionContext接口的Javadocs.可以看到它仅定义了一个方法currentSession()。它的实现类负责追踪current contextual session。同时Hibernate提供了对该接口的三种实现:

前两种实现提供了"one session - one database transaction"编程模型,也被用为session-per-request。一个Session的开始和结束由一个 database transaction来定义。If you use programmatic transaction demarcation in plain JSE without JTA,建议你使用Hibernate Transaction API来隐藏底层实现。如果你是用JTA,你可以利用JTA接口来界定transactions。如果你在支持CMT的EJB容器中运行,transaction的边界可以声明性的定义,而且在你的代码中不需要任何界定transaction和session的操作。

配置参数hibernate.current_session_context_class用来定义使用org.hibernate.context.spi.CurrentSessionContext的哪一个实现类。为了向后兼容,如果这个参数没有设置,但是设置了org.hibernate.transaction.TransactionManagerLookup的值,Hibernate就会使用org.hibernate.context.internal.JTASessionContext。通常hibernate.current_session_context_class的值就是你要使用的实现类的名字。对于上面提到的三个实现,它们各自有对应的短名字"jta", "thread", 和"managed".

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Struts2 和 Hibernate 的登录和注册的完整实例。 首先,需要创建一个名为 `User` 的 JavaBean 类,用于表示用户信息: ```java public class User { private int id; private String username; private String password; // getters and setters } ``` 接下来,需要配置 Hibernate 的 `SessionFactory`,以便在操作数据库时使用。可以在 `hibernate.cfg.xml` 文件中进行配置: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:mysql://localhost:3306/test?useSSL=false</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.MySQLDialect</property> <property name="show_sql">true</property> <mapping class="com.example.User"/> </session-factory> </hibernate-configuration> ``` 接着,需要创建一个名为 `UserDao` 的类,用于操作数据库。在该类中,需要使用 Hibernate 的 API 进行增删改查操作: ```java public class UserDao { private SessionFactory sessionFactory; public UserDao() { Configuration configuration = new Configuration().configure(); sessionFactory = configuration.buildSessionFactory(); } public void addUser(User user) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(user); tx.commit(); } catch (HibernateException e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } } public User getUserByUsername(String username) { Session session = sessionFactory.openSession(); Transaction tx = null; User user = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from User where username = :username"); query.setString("username", username); user = (User) query.uniqueResult(); tx.commit(); } catch (HibernateException e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return user; } } ``` 然后,需要创建一个名为 `UserAction` 的类,用于处理用户登录和注册的请求。在该类中,需要使用 Struts2 的 API 进行请求处理: ```java public class UserAction extends ActionSupport { private User user; private String confirmPassword; private UserDao userDao = new UserDao(); public String login() { User savedUser = userDao.getUserByUsername(user.getUsername()); if (savedUser == null || !savedUser.getPassword().equals(user.getPassword())) { addActionError("Invalid username or password!"); return INPUT; } return SUCCESS; } public String register() { if (!user.getPassword().equals(confirmPassword)) { addActionError("Passwords don't match!"); return INPUT; } User savedUser = userDao.getUserByUsername(user.getUsername()); if (savedUser != null) { addActionError("Username already exists!"); return INPUT; } userDao.addUser(user); return SUCCESS; } // getters and setters } ``` 最后,需要在 `struts.xml` 文件中进行配置,以便 Struts2 能够正确地处理请求: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.devMode" value="true"/> <package name="default" extends="struts-default"> <action name="login" class="com.example.UserAction" method="login"> <result name="success">/success.jsp</result> <result name="input">/login.jsp</result> </action> <action name="register" class="com.example.UserAction" method="register"> <result name="success">/success.jsp</result> <result name="input">/register.jsp</result> </action> </package> </struts> ``` 其中,`success.jsp` 是登录或注册成功后显示的页面,`login.jsp` 和 `register.jsp` 分别是登录和注册的页面。 这样,基于 Struts2 和 Hibernate 的登录和注册功能的完整实例就完成了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值