Hibernate查询结果为空

时间:2012-11-21 18:53:12

标签: java mysql hibernate

我正在学习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;
}

}

请帮忙,因为我在这个问题上无法归零?

2 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。我通过在创建查询之前开始事务并在打印数据之后提交来修复它。我不知道为什么我需要有一个事务来查询数据库。

答案 1 :(得分:0)

在测试中遇到了相同的问题:

@Test
public void readMessage() {
    try (Session session = factory.openSession()) {
        List<Message> list = session.createQuery("from Message", Message.class).list();
        assertEquals(list.size() > 3, true);
    }
}

在您的<property name="hbm2ddl.auto">update</property>文件中使用:hibernate.cfg.xml

参考:What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do