コード例 #1
0
 /**
  * 执行Hql语句
  *
  * @param hql
  * @return
  */
 private static List hql(String hql) {
   Session session = null;
   Transaction trans = null;
   try {
     session = HibernateSessionFactory.getSession();
     trans = session.beginTransaction();
     List stus = session.createQuery(hql).list();
     trans.commit();
     return stus;
   } catch (Exception e) {
     e.printStackTrace();
     if (trans != null) {
       trans.rollback();
     }
     throw new RuntimeException(e.getMessage());
   } finally {
     if (session != null && session.isOpen()) {
       HibernateSessionFactory.closeSession();
     }
   }
 }
コード例 #2
0
 /**
  * 查询单个对象
  *
  * @param id
  */
 private static void getStu() {
   Session session = null;
   Transaction trans = null;
   try {
     session = HibernateSessionFactory.getSession();
     trans = session.beginTransaction();
     // 确认最多只有一条才用
     Student stu =
         (Student) session.createQuery("from Student where id='20040001'").uniqueResult();
     trans.commit();
     System.out.println(stu.getSname());
   } catch (Exception e) {
     e.printStackTrace();
     if (trans != null) {
       trans.rollback();
     }
     throw new RuntimeException(e.getMessage());
   } finally {
     if (session != null && session.isOpen()) {
       HibernateSessionFactory.closeSession();
     }
   }
 }