Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: select cat0_.id as id1_0_, cat0_.createDate as createDa2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother5_0_, cat0_.name as name4_0_ from tb_cat cat0_
======================
ID1
nameMary
DescriptionI am the Mother
Exception in thread "main" java.lang.NullPointerException at cn.lora.hibernate.test.CatTest.main(CatTest.java:45)部分原代码:
List<Cat> list = s.createQuery("from Cat").list();
for (Cat cat : list) {
System.out.println("======================");
System.out.println("ID"+cat.getId());
System.out.println("name"+cat.getName());
System.out.println("Description" + cat.getDescription());
System.out.println("mother"+cat.getMother() == null ? "我没有mother" : cat.getMother().getName());
}

s.close();
我知道是这里的cat.getMother() 为空,但是应该怎么解决这个空指针异常问题呢

解决方案 »

  1.   

    第一种可能,你数据库里有mother这个外键为空,没传进去值、你可以去数据库里看一下,
    第二种可能,就是你的配置文件有问题了,第一种可能性比较大,自己看看吧
      

  2.   

    ==null和"".equals(cat.getMother())都要判断
      

  3.   

    可能是你配置的对于Mother这个外键关联的对象是不抓去的。看看你的实体bean的配置或者是hbm.xml文件的配置吧。
      

  4.   

    for (Cat cat : list) {
    System.out.println("======================");
    System.out.println("ID:"+cat.getId());
    System.out.println("name:"+cat.getName());
    if (cat.getMother() == null)
    motherName = "我没有mother";
    else 
    motherName = cat.getMother().getName();

    System.out.println("Description:" + cat.getDescription());
    System.out.println("mother:"+ motherName);
    }把代码修改成这样子,就没有空指针问题了