我试图用Hibernate和Spring在HQL中保存一个对象到我的MySQL数据库中。但是,在保存时,下面是错误消息:
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常为java.lang.NullPointerException
public void addCountry(Country country) throws Exception {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//Add new Country object
Country c = new Country();
c.setId(""); //id value is auto into mySQL
c.setCity1(country.getCity1());
c.setCity2(country.getCity2());
session.save(c);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw e;
} finally {
session.close();
}
}发布于 2017-11-17 10:30:02
正如juanlumn所说,删除setId(""),因为Hibernate将为您创建此功能。需要调试以查看哪个对象导致了NullPointerException,就像需要知道是否正在进行Hibernate会话一样,这将使您知道您已经正确配置了Hibernate。同样,您正在将country作为方法参数传递,但是通过在dao本身中填充来保存c,不知道为什么。
https://stackoverflow.com/questions/47336892
复制相似问题