一.导入相应的包,选用Hibernate-4.1.7版本
1.hibernate安装文件中lib->required的包
2.导入log4j
3.数据库驱动

二.创建hibernate的配置文档
在src下创建相应的hibernate.cfg.xml并配置相应的数据库基本信息(xml文件可在Hibernate安装文件中复制再修改)
首先得配置数据库的基本连接

//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>
<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/hiber</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>

 

三.创建实体类

package org.znufe.model;

import java.util.*;

public class User {
private int id;
private String name;
private Date born;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBorn() {
return born;
}
public void setBorn(Date born) {
this.born = born;
}

}

四.在实体类的包中创建相应的hbm文件,用来指定实体类和数据库映射

//User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.znufe.model">
<class name="User" table="h_user">
<id name ="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="born" type="timestamp"/>
</class>
</hibernate-mapping>

 

五.将配置文件添加到hibernate的cfg的配置文件中
在cfg中添加<mapping resource="org/znufe/model">
*注:文件路径用/

六.创建SessionFactory,SF是线程安全的,整个SF应该基于单例模式创建
Configuration cfg = new Configuration().configure();
//cfg.buildSessionFactory();这个方法在4中被禁用了
//先得创建ServiceRegistry
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);

七.创建Session
Session session = factory.openSession();

八.通过Seesion进行操作,例如插入一个对象User(int id, String name, Date born)

try {
session = factory.openSession();
//开启事务
session.beginTransaction();

User u = new User();
u.setName("张三");
u.setBorn(new Date());
session.save(u);

//提交事务
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(session != null)
session.getTransaction().rollback();
}finally
{
if(session != null)
session.close();

}
}