HibernateSessionFactoryUtil类提供了一个getSessionFactory()静态方法。
通过调用此方法可以返回一个SessionFactory对象。
在其他地方创建Session对象的时候:
只需要这样一句代码:
Session session =
HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
这样既可获得Session对象。
在hibernate.cfg.xml
<session-factory></session-factory>中加入下列代码:
<property
name="current_session_context_class">thread</property>
注意<property></property>必须要放在<mapping></mapping>上面
HibernateTest类封装了对数据操作更删改查的基本方法。
根据不同的业务逻辑环境代码作出相应的变更即可使用。
HibernateSessionFactoryUtil.java
- package com.xiami.util;
-
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
-
- public class HibernateSessionFactoryUtil {
- private static final SessionFactory sessionFactory;
- static {
- try {
- sessionFactory = new Configuration().configure().buildSessionFactory();
- } catch (Throwable ex) {
- /*
* 需要
捕获Throwable对象, 否则捕获不到
Error及其子类,以及NoClassDefFoundError类型的错误
*/
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- private HibernateSessionFactoryUtil() {
-
- }
-
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
HibernateTest.java
- package com.xiami.examples;
-
- import org.hibernate.Session;
- import org.hibernate.Transaction;
-
- import com.xiami.util.HibernateSessionFactoryUtil;
-
- public class HibernateTest {
- public static void main(String args[]){
- HibernateTest test = new HibernateTest();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Guestbook gb = test.getGuestbook(1);
- System.out.println(gb.getName());
- }
-
-
-
-
- public void addGuestbook(Guestbook gb){
- Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
- Transaction tx = session.beginTransaction();
- session.save(gb);
- tx.commit();
- }
-
-
-
-
- public void deleteGuestbook(Integer id){
- Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
- Transaction tx = session.beginTransaction();
-
-
-
-
-
-
-
-
-
-
- Guestbook gb = getGuestbook(id);
- session.delete(gb);
- tx.commit();
- }
-
-
-
-
- public boolean
updateGuest(Guestbook gb){
-
- Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
- Transaction tx = session.beginTransaction();
-
try {
-
session.update(gb);
-
tx.commit();
-
return true;
-
}catch(Exception e){
-
return false;
-
}
- }
-
-
-
-
- public Guestbook getGuestbook(Integer id){
- Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
- Transaction tx = session.beginTransaction();
- Guestbook gb = new Guestbook();
- gb = (Guestbook) session.get(Guestbook.class, new Integer(id));
- return gb;
- }
- }
HibernateSessionFactoryUtil类的增,删,改,查,布布扣,bubuko.com
HibernateSessionFactoryUtil类的增,删,改,查
原文:http://www.cnblogs.com/ZHANYU/p/3618803.html