步骤:
1.配置hibernate.cfg.xml文件配置属性
<!-- 配置管理Session的方式 -->
<property name="current_session_context_class">thread</property>
2.HibernateUtils 创建SessionFactory 获取Session 获取SessionFactory
public class HibernateUtils {
private SessionFactory sessionFactory;
private static HibernateUtils hUtils = new HibernateUtils();
private HibernateUtils() {
}
// 获取SessionFactory
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();// 配置文件configure()
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
return sessionFactory;
}
// 获取Session
public Session getSession() {
return getSessionFactory().getCurrentSession();// 获取当前线程绑定的Session
}
public static HibernateUtils gethUtils() {
return hUtils;
}
}
3.创建Dao类
- 1.传入Session,会导致上一层和hibernate紧密耦合 不推荐
- 2.获取与当前线程绑定Session 是同一个 多个Dao可以使用同一个事务
public class DepartmentDao {
/**
* 1.传入Session,会导致上一层和hibernate紧密耦合 不推荐
* 2.获取与当前线程绑定Session 是同一个 多个Dao可以使用同一个事务
*
*
* */
public void save(Department dept) {
Session session = HibernateUtils.gethUtils().getSession();
session.save(dept);
System.out.println("保存");
}
}
业务调用
//1.配置文件配置属性
public static void manageSession() {
//开启事务
Transaction transaction = HibernateUtils.gethUtils().getSession().beginTransaction();
DepartmentDao dao=new DepartmentDao();
Department dept = new Department();
dept.setName("绑定");
Department dept1 = new Department();
dept1.setName("绑定1");
Department dept2 = new Department();
dept2.setName("绑定2");
dao.save(dept);
dao.save(dept1);
dao.save(dept2);
//提交事务
transaction.commit();
}
使用Spring时不用这些
批量处理
//建议使用JDBC API
public static void batch() {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();// 配置文件configure()
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
//这里处理效率最高
}
});
transaction.commit();
session.close();
sessionFactory.close();
}