我有一个实体:
@Entity @Table(name = "smsc.security_users") public class User { @Id @Column(name = "id") private int id; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "enabled") private int enabled; @Column(name = "master_id", nullable = true) private Integer master_id; @Temporal(TemporalType.TIMESTAMP) @Column(name = "passwordExpiration") private Date passwordExpiration; public String getUsername() { return username; } ...
我在说master_id。这是我的DAO方法:
master_id
public void add(String userName, String password, Integer master_id) { Session session = null; session = this.sessionFactory.getCurrentSession(); Query query = session .createSQLQuery( "INSERT INTO smsc.security_users(id,username,password,enabled,passwordExpiration,master_id) VALUES(smsc.SeqDictID.nextval+1,:userName,:password,1,:passwordExpiration,:master_id)") .setString("userName", userName) .setString("password", Sha1.getHash(password)) .setTimestamp("passwordExpiration", DateUtil.getTomorrow()) .setInteger("master_id", master_id); int updated = query.executeUpdate(); }
日志说:
请求处理失败;嵌套的异常是java.lang.NullPointerException
并将指针放在这一行:
.setInteger("master_id", master_id);
master_id有时必须为null。那么如何设置null?
如果您查看Query类的文档,setInteger()方法,
Query setInteger(String name,int val)
它以名称和 原始类型int 作为参数。
当您在 自动装箱 期间传递值为null的包装器类型Integer时,会发生空指针Exception。
例如:
Integer x = null; int y = x; // gives a nullpointer exception.
你可以用
Query setParameter(String name, Object val, Type type);
设置空值的方法。
也可以看看: ```