1.核心配置文件
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置JDBC驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 配置数据库密码 -->
<property name="hibernate.connection.password">123456</property>
<!-- 连接数据库URL -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysqldb</property>
<!-- 配置数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置JDBC内置连接池 -->
<property name="connection.pool_size">1</property>
<!-- 配置数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 输出运行时生成的SQL语句-->
<property name="show_sql">true</property>
<!-- 列出所有的映射文件 -->
<mapping resource="org/hibernate/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2.目录
org.hibernate.entity
1.实体类
注意:必须有一个标识键 2.必须有一个默认的构造方法
User.java
package org.hibernate.entity;
public class User {
private int id;//2.必须有一个标识属性,主键
private String name;
private String password;
private String type;
//1,必须有默认的构造方法,这样hibernate就可以运用Java的反射机制啦
public User() {
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ ", type=" + type + "]";
}
}
2.User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hibernate.entity.User" table="USER">
<id name="id" type="java.lang.Integer" column="USER_ID">
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="20"></column>
</property>
<property name="password" type="java.lang.String" >
<column name="PASSWORD" length="12"></column>
</property>
<property name="type" type="java.lang.String" >
<column name="TYPE" length="6"></column>
</property>
</class>
</hibernate-mapping>
3.辅助工具类
package org.hibernate.entity;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//辅助工具库勒
public class HibernateUntil {
private static SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
// 创建线程局部变量threadLocal。用来保存Hibernate的session
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// 使用静态代码块初始化Hbernate
static {
try {
// 读取配置文件hibernate.cfg.xml
//new Configuration()方法被调用时Hibernate再ClassPath目录小查找hibernate.properies文件
//configure()方法呗调用时会再classpath的根目路下查找hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
// 创建SessionFactory
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable e) {
throw new ExceptionInInitializerError(e);
}
}
// 获取Sessionfactory实例
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
// 获取ThreadLocal对象管理的Session实例
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
// 通过sessionfactoory对象创建session对象
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
// 将新打开的实例保存到线程局部变量threadLocal中
threadLocal.set(session);
}
return session;
}
// 关闭session实例
public static void closeSession() throws HibernateException {
// 从县城局部变量threadLocal中获取之前存入的Session实例
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
// 重建SessionFactory
public static void rebuildSessionFactory() {
try {
// 读取配置文件hibernate.cfg.xml
configuration.configure("/hibernate.cfg.xml");
// 创建SessionFactory
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
// TODO: handle exception
}
}
// 关闭缓存连接池子
public static void shutdown() {
getSessionFactory().close();
}
}
3.org.hibernate.dao
1.UserDao.java
package org.hibernate.dao;
import java.util.List;
import org.hibernate.entity.User;
//创建UserDAO接口
public interface UserDao {
void save(User user); //添加用户
User findById(int id); //根据用户标识查找指定用户
void delete(User user); //删除用户
void update(User user); //修改用户信息
}
2.UserDaoImpl.java
package org.hibernate.dao;
import org.hibernate.*;
import org.hibernate.entity.*;
public class UserDaoImpl implements UserDao {
// 添加用户
public void save(User user) {
Session session = HibernateUntil.getSession(); // 生成Session实例
Transaction tx = session.beginTransaction(); // 创建Transaction实例
try {
session.save(user); // 使用Session的save方法将持久化对象保存到数据库
tx.commit(); // 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback(); // 回滚事务
} finally {
HibernateUntil.closeSession(); // 关闭Session实例
}
}
// 根据用户标识查找指定用户
public User findById(int id) {
User user = null;
Session session = HibernateUntil.getSession(); // 生成Session实例
Transaction tx = session.beginTransaction(); // 创建Transaction实例
try {
user = (User) session.get(User.class, id); // 使用Session的get方法获取指定id的用户到内存中
tx.commit(); // 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback(); // 回滚事务
} finally {
HibernateUntil.closeSession(); // 关闭Session实例
}
return user;
}
// 删除用户
public void delete(User user) {
Session session = HibernateUntil.getSession(); // 生成Session实例
Transaction tx = session.beginTransaction(); // 创建Transaction实例
try {
session.delete(user); // 使用Session的delete方法将持久化对象删除
tx.commit(); // 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback(); // 回滚事务
} finally {
HibernateUntil.closeSession(); // 关闭Session实例
}
}
// 修改用户信息
public void update(User user) {
Session session = HibernateUntil.getSession(); // 生成Session实例
Transaction tx = session.beginTransaction(); // 创建Transaction实例
try {
session.update(user); // 使用Session的update方法更新持久化对象
tx.commit(); // 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback(); // 回滚事务
} finally {
HibernateUntil.closeSession(); // 关闭Session实例
}
}
}
3.DAOFactory.java
package org.hibernate.dao;
public class DAOFactory {
//返回USERDAO实现类的实例
//避免出现多种数据库时,多余的灭必要的修改
public static UserDao getUserDaoInstance()
{
return new UserDaoImpl();
}
}