步驟:
1.配置hibernate.cfg.xml文件配置屬性
<!-- 配置管理Session的方式 -->
<property name="current_session_context_class">thread</property>
2.HibernateUtils 創(chuàng)建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();// 獲取當(dāng)前線程綁定的Session
}
public static HibernateUtils gethUtils() {
return hUtils;
}
}
3.創(chuàng)建Dao類
- 1.傳入Session硅堆,會(huì)導(dǎo)致上一層和hibernate緊密耦合 不推薦
- 2.獲取與當(dāng)前線程綁定Session 是同一個(gè) 多個(gè)Dao可以使用同一個(gè)事務(wù)
public class DepartmentDao {
/**
* 1.傳入Session塌碌,會(huì)導(dǎo)致上一層和hibernate緊密耦合 不推薦
* 2.獲取與當(dāng)前線程綁定Session 是同一個(gè) 多個(gè)Dao可以使用同一個(gè)事務(wù)
*
*
* */
public void save(Department dept) {
Session session = HibernateUtils.gethUtils().getSession();
session.save(dept);
System.out.println("保存");
}
}
業(yè)務(wù)調(diào)用
//1.配置文件配置屬性
public static void manageSession() {
//開啟事務(wù)
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);
//提交事務(wù)
transaction.commit();
}
使用Spring時(shí)不用這些
批量處理
//建議使用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();
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者