1. 下载资源:

2. 资源介绍

  • hibernate-release-X.X.XX.Final
    • documentation 相关文档
    • lib 相关jar包
    • project相关资源文件,模板文件,源码等

3. 搭建hibernate环境:

3.1 新建一个java项目

3.2 导入相关jar包

【./lib/required】和SQL包

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-x.x.xx.Final.jar
  • hibernate-core-x.x.xx.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • jandex-x.x.xx.Final.jar
  • javassist-3.18.1-GA.jar
  • jboss-logging-x.x.x..Final.jar
  • mysql-connector-java-5.1.20-bin.jar

4. 编写配置文件hibernate.cfg.xml文件

提取hibernate-release-x.x.xx.Final\project\etc\hibernate.cfg.xml 放入到项目中src下:

1
2
3
4
5
6
7
8
9
10
11
12
<hibernate-configuration>
<session-factory>
<!-- 配置数据库连接信息 -->
<property n
ame="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
</session-factory>
</hibernate-configuration>

5. 创建数据库表,以及对应的pojo对象

5.1 pojo对象

1
2
3
4
5
public class User {
private int id;
private String name;
private String pwd;
}

5.2 User表:user

id name pwd

6. 编辑*.hbm.xml文件

文件名一般为pojo类的名称User.hbm.xml,放在pojo类所在的包下,头文件可以在project下查找,也可拷贝。

1
2
3
4
5
6
7
8
9
10
11
12
<hibernate-mapping>
<!-- 类路径和表名 -->
<class name="com.forever.pojo.User" table="user">
<!-- 主键生成策略 -->
<id name="id">
<generator class="native"></generator>
</id>
<!-- 实体类的属性 -->
<property name="name"/>
<property name="pwd"/>
</class>
</hibernate-mapping>

7. 将*.hbm.xml配置文件加入到hibernate.cfg.xml

1
2
在hibernate.cfg.xml文件中的<session-factory>中添加映射,resource值为*.hbm.xml文件的路径
<mapping resource="com/forever/pojo/User.hbm.xml" />

8. 测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public static void main(String[] args) {
// 1.加载Hibernate的核心配置文件
Configuration configuration = new Configuration().configure();
// 手动加载映射
// configuration.addResource("com/forever/pojo/User.hbm.xml");

// 2.创建一个SessionFactory对象:类似于JDBC中连接池
// 【3.x以前的写法】
// SessionFactory sessionFactory = configuration.buildSessionFactory();

// 【4.0~4.3的用法】
// ServiceRegistry sr = new ServiceRegistryBuilder()
// .applySettings(configuration.getProperties())
// .buildServiceRegistry();

// 【4.3之后的用法】
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
SessionFactory sf = configuration.buildSessionFactory(registry);

// 3.通过SessionFactory获取到Session对象:类似于JDBC中Connection
Session session = sessionFactory.openSession();

// 4.手动开启事务:
Transaction transaction = session.beginTransaction();

//5.保存数据
User user = new User();
user.setName("张三疯");
user.setPwd("1111");
session.save(user);

//6.提交事务
tx.commit();
//7.关闭session
session.close();
}