1.Hibernate配置文件
Hibernate通过读取默认的XML配置文件hibernate.cfg.xml加载数据库的配置信息,改配置文件默认存储于classpath根目录下。
Hibernate配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库连接的URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/表的名称</property>
<!-- 数据库连接用户名 -->
<property name="connection.username">用户名</property>
<!-- 数据库连接密码 -->
<property name="connection.password">连接密码</property>
<!-- Hibernate方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 映射文件 -->
<mapping resource="employee/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2.编写持久化类
假设有一个数据库user表,有id, name,sex,business,address,remark6个字段,编写持久化类如下所示:
public class Employee {
private Integer id;//id值
private String name;//员工姓名
private String sex;//性别
private String business;//职务
private String address;//住址
private String remark;//备注
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBusiness() {
return business;
}
public void setBusiness(String business) {
this.business = business;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
这是一个普通类,没有特殊功能且不依赖于任何对象,但创建时需要注意一下几点:
1.必须要声明一个默认的无参的构造方法。
2.类的声明是非final类型的。
3.为属性声明get和set方法。
3.编写映射文件
Hibernate的映射文件和持久化类相呼应,映射文件指定持久化类和数据表之间的映射关系。其命名方式规范为*.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>
<class name="employee.Employee" table="tb_employee">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 姓名 -->
<property name="name" type="string" length="45">
<column name="name"/>
</property>
<!-- 性别 -->
<property name="sex" type="string" length="1">
<column name="sex"/>
</property>
<!-- 职务 -->
<property name="business" type="string" length="45">
<column name="business"/>
</property>
<!-- 地址 -->
<property name="address" type="string" length="100">
<column name="address"/>
</property>
<!-- 备注 -->
<property name="remark" type="string" length="200">
<column name="remark"/>
</property>
</class>
</hibernate-mapping>
4.编写Hibernate的初始化类
package com.wgh.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static SessionFactory sessionFactory = null; // SessionFactory对象
// 静态块
static {
try {
Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
sessionFactory = cfg
.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取Session
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* 重建会话工厂
*/
public static void rebuildSessionFactory() {
try {
Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
sessionFactory = cfg
.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取SessionFactory对象
*
* @return SessionFactory对象
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 关闭Session
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close(); // 关闭Session
}
}
}