我正在尝试使用 Hibernate 和 Spring 在 HQL 中将对象保存在我的 MySQL 数据库中。 但是,保存时出现错误消息:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is 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();
}
}
最佳答案
正如 juanlumn 所说,删除 setId("") 因为 Hibernate 会为你创建这个。需要调试以查看哪个对象导致 NullPointerException,就像需要知道您是否正在获取 Hibernate session 一样,这将让您知道您已正确配置 Hibernate。同样,您将国家/地区作为方法参数传递,但通过填充 dao 本身来保存 c,不知道为什么。
关于保存对象/Hibernate 时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336892/