2012-11-21 69 views
0

我正在學習hibernate,並製作了一個簡單的程序從我的sql中讀取一個表。
執行查詢後得到的結果列表的大小爲零,即使表中有14條記錄。
我做了show_sql查看SQL日誌,我得到這個:
休眠查詢結果爲空

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). 
log4j:WARN Please initialize the log4j system properly. 
Hibernate: select insurance0_.lngInsuranceId as col_0_0_ from insurance insurance0_ 

我還附上代碼供參考

Session session = new Configuration().configure("Hibernate.cfg.xml").buildSessionFactory().openSession(); 

    String SQL_QUERY ="from Insurance insurance"; 
    Query query = session.createQuery(SQL_QUERY); 
    System.out.println("size of list is: "+query.list().size()); 
    List resultList = query.list(); 

    for (Iterator iterator = resultList.iterator(); iterator.hasNext();) { 
     Insurance object = (Insurance) iterator.next(); 
     System.out.println("insurance name is: "+object.getInsuranceName()); 
     System.out.println("insurance amount is: "+object.getInvestementAmount()); 

    } 
    session.close(); 

實體類:

public class Insurance { 

    private long lngInsuranceId; 
    private String insuranceName; 
    private int investementAmount; 
    private Date investementDate; 
public long getLngInsuranceId() { 
    return lngInsuranceId; 
} 
public void setLngInsuranceId(long lngInsuranceId) { 
    this.lngInsuranceId = lngInsuranceId; 
} 
public String getInsuranceName() { 
    return insuranceName; 
} 
public void setInsuranceName(String insuranceName) { 
    this.insuranceName = insuranceName; 
} 
public int getInvestementAmount() { 
    return investementAmount; 
} 
public void setInvestementAmount(int investementAmount) { 
    this.investementAmount = investementAmount; 
} 
public Date getInvestementDate() { 
    return investementDate; 
} 
public void setInvestementDate(Date investementDate) { 
    this.investementDate = investementDate; 
} 

}

Ple因爲我無法在這個問題上歸零

+1

你可以發佈你的實體類嗎? – invariant

+0

你確定你指向正確的數據庫嗎? –

+0

爲了確保我指向正確的DB。我用hibernate插入了一條新記錄。它正常工作 –

回答

2

我有同樣的問題。我通過在打印數據之後創建查詢和提交之前開始事務來修復它。我不知道爲什麼我需要有一個事務來查詢數據庫。

+0

謝謝,我在創建查詢之前添加了'session.beginTransaction()。commit()'並解決了問題。我不問爲什麼,我傾向於在未來的項目中不再使用hibernate – benez