首先写一个简单的实体类Student
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student { private Long id; private String name; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
再写一个查询Student的HQL语句,用setLong的方法赋一个null值
package test.run; import org.hibernate.Session; import org.hibernate.tutorial.util.HibernateUtil; import test.domain.Student; public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student student = new Student(); student.setId(null); Student result = (Student) session.createQuery("from Student where id =:id").setLong("id", student.getId()).uniqueResult(); System.out.println(result); session.getTransaction().commit(); } }
程序运行后,会抛出java.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException at test.run.Test.main(Test.java:16)
将setLong方法换成setParameter(String name, Object val, Type type),就不会出现NullPointerException的异常。
API文档描述如下:
Parameters:
name
- the name of the parameter
val
- the possibly-null parameter value
type
- the Hibernate type
可知val的值是可以为空的。
import org.hibernate.Session; import org.hibernate.tutorial.util.HibernateUtil; import org.hibernate.type.StandardBasicTypes; public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student student = new Student(); student.setId(null); Student result = (Student) session.createQuery( "from Student where (id =:id)").setParameter("id", student.getId(), StandardBasicTypes.LONG) .uniqueResult(); System.out.println(result); session.getTransaction().commit(); } }