---
title: "hibernate4.1的入门初步"
author: "hyneng"
date: "2013-03-29T16:30:43Z"
tags: []
categories: ["行业应用"]
slug: "hibernate4-1"
draft: false
lastmod: "2013-04-03T19:11:50Z"
id: 1838844
url: "https://itway.iteye.com/blog/1838844"
---

**一、导入相应的包**

1、hibernate安装文件夹中的lib-&gt;required中的包

2、导入log4j

3、导入数据库驱动

 

**二、创建hibernate的配置文件**

在src的目录下创建相应的hibernate.cfg.xml在这个文件中加入相应的数据库基本信息的配置

在hibernate.cfg.xml的配置文件中首先需要配置相应的数据库基本连接

 

```
<!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>
        <!-- hibernate的方言，用来确定连接的数据库 -->
    <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
    <!-- 数据库的连接类 -->
    <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
    <!-- 数据库的连接字符串和用户名密码 -->
    <property name="hibernate.connection.url">
            jdbc:mysql://localhost:3306/itat_hibernate
        </property>
    <property name="hibernate.connection.username">
            root
        </property>
    <property name="hibernate.connection.password">
            123456
        </property>
    <!-- 在使用hibernate时会显示相应的SQL -->
    <property name="show_sql">true</property>
    <!-- 会自动完成类到数据表的转换 -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>
```

 

 

**三、创建实体类**

 

```
package org.zttc.itat.model;
import java.util.Date;
public class User {
    private int id;
    private String username;
    private String password;
    private String nickname;
    private Date born;
      
    //set get方法省略
}
```

 

 

**四、在实体类的包中创建相应的hbm文件，用来指定实体类和数据库映射关系**

User.hbm.xml

 

```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  
<hibernate-mapping package="org.zttc.itat.model">
    <class name="User" table="t_user">
        <id name="id">
            <generator class="native"/>
        </id>
    <property name="username"/>
    <property name="password"/>
    <property name="nickname"/>
    <property name="born" type="timestamp"/>
    </class>
</hibernate-mapping>
```

 

 

**五、将配置文件添加到hibernate的cfg的配置文件中**

```
<!-- 加入实体类的映射文件 --> 
<mapping resource="org/zttc/itat/model/User.hbm.xml"/>
```

 

**六、创建SessionFactory,SessionFactory是线程安全，所以整个SessionFactory应该基于单例的模式来创建**

```
Configuration cfg = new Configuration().configure();
//在hibernate3中都是使用该种方法创建，但是在4中被禁用了
//cfg.buildSessionFactory();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
    .applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
```

 

**七、创建session**

Session session = factory.openSession();

 

**八、通过session来进行各种操作**

 

六、七、八的完整代码如下：

```
@Test
public void test01() {
    Configuration cfg = new Configuration().configure();
    //在hibernate3中都是使用该种方法创建，但是在4中被禁用了
    //cfg.buildSessionFactory();
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
    .applySettings(cfg.getProperties()).buildServiceRegistry();
    SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
    Session session = null;
    try {
    session = factory.openSession();
    //开启事务
    session.beginTransaction();
    User u = new User();
    u.setNickname("张三");
    u.setPassword("123");
    u.setUsername("zhangsan");
    u.setBorn(new Date());
    session.save(u);
    //提交事务
    session.getTransaction().commit();
    } catch (HibernateException e) {
    e.printStackTrace();
    if(session!=null)
        session.getTransaction().rollback();
    } finally {
    if(session!=null) session.close();
    }
}
```

 

相关文章

[](http://www.656463.com/article/393)

[Hibernate实现了原生态的SQL查询](http://www.656463.com/article/425)

[](http://www.656463.com/article/393)

[Hibernate的最佳实践](http://www.656463.com/article/424)

[](http://www.656463.com/article/393)

[hibernate悲观锁与乐观锁](http://www.656463.com/article/423)

[](http://www.656463.com/article/393)

[hibernate查询缓存](http://www.656463.com/article/421)

[](http://www.656463.com/article/393)

[hibernate二级缓存](http://www.656463.com/article/420)

[](http://www.656463.com/article/393)

[hibernate一级缓存及N+1问题](http://www.656463.com/article/419)

[](http://www.656463.com/article/393)

[hibernate抓取策略](http://www.656463.com/article/418)

[](http://www.656463.com/article/393)

[常用HQL(Hibernate Query Language)查询](http://www.656463.com/article/417)

[](http://www.656463.com/article/393)

[学习hibernate高级特性之前](http://www.656463.com/article/416)

[](http://www.656463.com/article/393)

[hibernate中基于annotation（注解）的many2many双向](http://www.656463.com/article/406)

[](http://www.656463.com/article/393)

[hibernate中基于annotation（注解）的One2One双向](http://www.656463.com/article/405)

[](http://www.656463.com/article/393)

[hibernate中基于annotation（注解）的one2Many双向](http://www.656463.com/article/404)

[](http://www.656463.com/article/393)

[基于annotation（注解）的hibernate4.1的入门初步](http://www.656463.com/article/403)

[](http://www.656463.com/article/393)

[hibernate中多对多映射关系](http://www.656463.com/article/402)

[](http://www.656463.com/article/393)

[hibernate中OneToOne双向](http://www.656463.com/article/401)

[](http://www.656463.com/article/393)

[hibernate中OneToOne单向](http://www.656463.com/article/400)

[](http://www.656463.com/article/393)

[hibernate中one2Many双向](http://www.656463.com/article/399)

[](http://www.656463.com/article/393)

[hibernate中one2Many单向](http://www.656463.com/article/398)

[](http://www.656463.com/article/393)

[hibernate中ManyToOne单向](http://www.656463.com/article/397)

[](http://www.656463.com/article/393)

[hibernate id 生成策略及主要使用方法](http://www.656463.com/article/396)

[](http://www.656463.com/article/393)

[hibernate延迟加载](http://www.656463.com/article/395)

[](http://www.656463.com/article/393)

[hibernate三种状态的讲解](http://www.656463.com/article/394)

[](http://www.656463.com/article/393)

[hibernate实现简单的CRUD](http://www.656463.com/article/393)

[](http://www.656463.com/article/393)

[hibernate4.1的入门初步](http://www.656463.com/article/392)

[](http://www.656463.com/article/393)

 

本文链接：[hibernate4.1的入门初步](http://www.656463.com/article/392 "hibernate4.1的入门初步"),领悟书生学习笔记，转载请注明出处[http://www.656463.com/article/392](http://www.656463.com/article/392 "hibernate4.1的入门初步")