Hibernate Core Reference Manual学习笔记——Chapter 1. Tutorial
Chapter 1. Tutorial
Table of Contents
1.1. Part 1 - The first Hibernate Application
1.1.1. Setup
1.1.2. The first class
1.1.3. The mapping file
1.1.4. Hibernate configuration
1.1.5. Building with Maven
1.1.6. Startup and helpers
1.1.7. Loading and storing objects
1.2. Part 2 - Mapping associations
1.2.1. Mapping the Person class
1.2.2. A unidirectional Set-based association
1.2.3. Working the association
1.2.4. Collection of values
1.2.5. Bi-directional associations
1.2.6. Working bi-directional links
1.3. Part 3 - The EventManager web application
1.3.1. Writing the basic servlet
1.3.2. Processing and rendering
1.3.3. Deploying and testing
1.4. Summary
1.1. Part 1 - The first Hibernate Application
JavaBean类有getter和setter方法,是一种推荐使用的设计模式。但对Hibernate而言并不是必须的。Hibernate可以直接访问类的属性。Hibernate可以访问public、private和protected修饰的getter和setter方法,就像它可以直接访问public、private和protected修饰的属性。
所有要被持久化的类都需要由无参的构造函数,因为Hibernate会使用反射来为你创建对象。构造函数可以是private的。however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.
Hibernate需要知道如何加载和保存持久化类的对象。这就是Hibernate配置文件的作用。配置文件告诉Hibernate去访问数据库中的哪张表,哪些列。
在Hibernate配置文件里使用的type不是java数据类型,也不是SQL数据类型,而是Hibernate映射类型。转换器可以从java类型转换到SQL类型,也可以反过来。如果没有配置type,Hibernate会尝试确定正确的映射类型。在某些场合下,这种使用java反射技术的自动检测并不能得出你期望的结果。比如说java.util.Date类型,Hibernate不知道是应该映射到SQL的date、timestamp还是time类型。同时这种自动检测会耗费时间和资源,如果注重性能,最好明确的配置type属性。
SessionFactory是一个全局的工厂,代表一个特定的数据库。如果你有好几个数据库,你应该在配置文件里配置多个SessionFactory。
If you give the org.hibernate.SessionFactory a name in your configuration, Hibernate will try to bind it to JNDI under that name after it has been built. Another, better option is to use a JMX deployment and let the JMX-capable container instantiate and bind a HibernateService to JNDI. Such advanced options are discussed later.涉及到很多陌生的名词,先看概念吧。
The getCurrentSession() method always returns the "current" unit of work.还记得我们在hibernate.cfg.xml文件中的配置吧
?
??映射文件中,inverse属性是用来干什么的呢?对于你,对于Java,一个双向连接就是一个简单的双方的引用。但是对Hibernate而言,它并没有足够的信息来正确组织SQL INSERT和UPDATE语句(从而避免约束冲突)。使某一侧的关联inverse,会告诉Hibernate将其看作是另一侧的镜像。这就是Hibernate为了解决从一个关系模型到数据库模式转换过程中出现的问题所需要的全部信息。
?写道规则很明确:所有双向关联都需要一侧inverse。在一对多关联中,必须是多的一边。在多对多关联中,你可以任选一边。??1.3. Part 3 - The EventManager web application
在一个request中使用一个Hibernate Session。而不是每一个数据库操作都使用一个Session。
the session-per-request pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern called Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.?