This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                2年前关闭。
            
                    
我试图通过session.createSQLQuery()方法在DATETIME类型列中插入日期和时间,并获取java.lang.NullPointerException。

提前致谢。

控制器类代码:

    package dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class AccountDAO {
    private HibernateTemplate template;
    Session session;
    int returnValue=0;

    public HibernateTemplate getTemplate() {
        return template;
    }
    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }
    public int insertLogoutTime(int srNum, String userName) {
        System.out.println("------>Inside AccountDAO<------");
        System.out.println("*************-- In insertLogoutTime() Method--************");
        try{
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            //System.out.println("update login_info set Logout_DateTime ='"+sdfDate.format(now)+"'" +" where SrNum= "+srNum+"");

            Query query=session.createSQLQuery("update login_info set Logout_DateTime =:theDate where SrNum=:srNum");
            query.setParameter("theDate", now);
            query.setParameter("srNum", srNum);
            returnValue= query.executeUpdate();
             System.out.println(returnValue);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return 0;
    }
}


错误:

17:50:21,167 ERROR [STDERR] java.lang.NullPointerException

最佳答案

不要像这样构建SQL。使用参数:

   Query query=session.createSQLQuery("update login_info set Logout_DateTime =:theDate where SrNum=:srNum");
    query.setParameter("theDate", now);
    query.setParameter("srNum", srNum);
    returnValue= query.executeUpdate();
     System.out.println(returnValue);


更新

尝试这个:

    query.setTimestamp("theDate", now);
    query.setString("srNum", srNum);

关于java - 无法使用session.createSQLQuery()方法在Hibernate中更新mySql中的DATETIME类型列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48113581/

10-11 01:28