简体   繁体   English

保存对象/ Hibernate上的java.lang.NullPointerException

[英]java.lang.NullPointerException on save object / Hibernate

I'm trying to save an object in my MySQL database with Hibernate and Spring, in HQL. 我试图在HQL中使用Hibernate和Spring将对象保存在我的MySQL数据库中。 However, when saving, here is the error message: 但是,保存时,错误消息如下:

org.springframework.web.util.NestedServletException: Request processing failed; org.springframework.web.util.NestedServletException:请求处理失败; nested exception is java.lang.NullPointerException 嵌套的异常是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();
    }
}

As juanlumn said remove setId("") as Hibernate will create this for you. 正如juanlumn所说的,因为Hibernate会为您创建setId(“”),所以将其删除。 Need to debug to see which object is causing NullPointerException like need to know if you are getting Hibernate session which will let you know that you have configured Hibernate properly. 需要调试以查看导致NullPointerException的对象,就像需要了解是否正在获取Hibernate会话一样,这将使您知道已正确配置了Hibernate。 Again you are passing country as method parameter but saving c by populating in dao itself not sure why. 同样,您将国家/地区作为方法参数传递,但是通过在dao本身中填充来保存c不确定为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM