2012-04-11 84 views
1

我正在嘗試編寫一個使用hibernate進行數據庫訪問的網站。保存我可以正常工作,但是當我嘗試調用getList方法執行session.createQuery調用時,代碼只是落入finally方法而沒有拋出異常,讓我有點困惑!Java,Hibernate getList不工作​​

代碼如下:

public List<Category> getCategories() { 
    //insertCategory(); 
    System.out.println("in get categories"); 
    List<Category> result = null; 
    Session session = HibernateUtil.getSessionfactory().openSession(); 
    Transaction transaction = null; 
    try { 
     transaction = session.beginTransaction(); 
     Query cats = session.createQuery("from category where is_parent = 1"); 
     result = cats.list(); 
     transaction.commit(); 
     for (java.util.Iterator<Category> it = result.iterator();it.hasNext();){ 
      Category myCategory = it.next(); 
      System.out.println(myCategory); 
     } 
     calculateBlueprintSize(result.size()); 
    } catch (HibernateException e) { 
     // TODO: handle exception 
     transaction.rollback(); 
     e.printStackTrace(); 
    } catch (Exception ee) { 
     ee.printStackTrace(); 
    } finally { 
     session.close(); 
    } 
    return result; 
} 

我插入正常工作(硬編碼,現在只是爲了證明我可以連接到DB)

public void insertCategory() { 
    Category newCat = new Category(); 
    newCat.setActive(new Integer(1)); 
    newCat.setCategoryDescription("my test category"); 
    newCat.setCategoryName("my cat name"); 
    newCat.setLastUpdatedDate(new Timestamp(new Date().getTime())); 
    newCat.setParent(new Integer(1)); 
    newCat.setSequence(new Integer(1)); 
    Session session = HibernateUtil.getSessionfactory().getCurrentSession(); 
    try { 
     session.beginTransaction(); 

     // user.setUserId(new Long(2)); 
     session.save(newCat); 
     session.getTransaction().commit(); 
    } finally { 
     session.close(); 
    } 

} 

氏是基於訪問MySQL數據庫。

任何幫助將不勝感激,我一直無法找到任何可以幫助我的東西,我是Hibernate的全新人物,所以開始思考使用原生sql與ehcache切換回DAO模式可能是最好的事情....

感謝

馬特

回答

2

我相信你是從createQuery調用得到一個RuntimeException,因爲你是用HQL名混合SQL名稱。我假設你的表名爲category,而is_parent列是該表中的一個字段。如果要使用HQL查詢,則需要使用Category實體上的屬性名稱,即parent而不是is_parent

+0

謝謝,但即使當我只有:查詢貓= session.createQuery(「從類別」);刪除where子句仍然失敗:( – Mattatattat 2012-04-11 21:15:55

+0

如果您處理了類路徑問題,那麼問題就會消失。 – 2012-04-11 21:42:05