本文是依照参考文档学习时的总结,参考文档原文:1.1. Part 1 - The first Hibernate Application

The mapping file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="me.hibernate.ex.domain">
<!-- all persistent entity classes need a mapping to a table in the SQL database -->
<class name="Event" table="EVENTS">
<!-- mapping the unique identifier property to the tables primary key -->
<id name="id" column="EVENT_ID">
<generator class="native" />
</id>
<property name="date" type="timestamp" column="EVENT_DATE" />
<!-- without the column attribute, Hibernate by default uses the property name as the column name -->
<property name="title" />
</class>
</hibernate-mapping>

映射文件Event.hbm.xml等同于.sql文件。

Hibernate configuration

文档中使用HSQLDB作为数据库,这里使用MySQL作为数据库,需要修改数据库连接设置,

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test</property>

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

同时添加依赖包mysql-connector-java-bin.jar

Startup and helpers

文档中提供的代码与最新的hibernate-core不匹配,需要修改buildSessionFactory()方法中的try块为:

1
2
3
4
5
6
7
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
}

[Solved] HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set中给出了详细的说明。

Loading and storing objects

文档中提供的代码使用args参数,这里将main函数简化为,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
Event theEvent = new Event();
theEvent.setTitle("Event");
theEvent.setDate(new Date());
session.save(theEvent);
session.getTransaction().commit();
} catch (Exception e) {
if (session.beginTransaction() != null)
session.beginTransaction().rollback();
} finally {
//session.close();
}
}

使用getCurrentSession()开始Session,在事务结束后,Hibernate会自动释放Session,如果使用session.close();会提示错误,

Session was already closed

如果使用文档中提供的代码,可以参考Eclipse里如何给main函数里的args参数赋值

现在运行EventManager.java可以看到,

Hibernate: insert into EVENTS (EVENT_DATE, title) values (?, ?)

查询本地MySQL数据库,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mysql> use test;
Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| events |
+----------------+
mysql> describe events;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| EVENT_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| EVENT_DATE | datetime | YES | | NULL | |
| title | varchar(255) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql>
Class Configuration & Interface SessionFactory(4.3)

创建SessionFactory时,Configuration实例允许应用指定即将使用的性质和映射文件,默认情况下使用hibernate.properties指定的性质。SessionFactry`是不可变的,不受Configuration变化的影响。

1
2
3
public Configuration configure() throws HibernateException{
}
// 使用hibernate.cfg.xml指定的性质和映射关系

应用一般创建单一的ConfigurationSessionFactory实例,然后实例化多个会话线程服务客户端的请求。

Interface Session(4.3)

Session是Java应用与Hibernate之间主要的运行时接口,Session的生命周期受到逻辑事务开始与结束的限制。Session的主要功能是对实体类的实例进行新建、读取和删除操作。

实例的三个阶段:

  1. transient,未关联任何Session;
  2. persistent,与唯一Session关联;
  3. detached,位于persistent之后,未关联任何Session。

实例的三个阶段

Session抛出异常时,事务必须回滚。