在Java中的Hibernate,當我們需要做一些與DB,我們需要: 1.打開會議 2.開始交易 3.完成交易 4.關閉會話會話和交易在Hibernate中的Java
例如,如果我想獲得學生名單:
public static List<Student> getStudentList() { List<Student> l = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { String hql = "from Student"; Query query = session.createQuery(hql); l = query.list(); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return l; }
插入一個學生
public static boolean addStudent(Student s) { Session session = HibernateUtil.getSessionFactory().openSession(); if (... /* check if student is already exists*/) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(s); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; }
爲什麼getStudentList()中沒有事務?在此先感謝