如何在Hibernate查询中将Integer参数设置为null?

时间:2014-09-04 14:20:33

标签: java hibernate

我有一个实体:

    @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方法:

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?

2 个答案:

答案 0 :(得分:21)

如果查看Query类的文档,请使用setInteger()方法

Query setInteger(String name,int val)

它采用名称和基本类型int 作为参数。

autoboxing 期间传递包含类型为Integer且值为null的情况时,会发生空指针异常。

例如:

Integer x = null;
int y = x;  // gives a nullpointer exception.

您可以使用

Query setParameter(String name,
                   Object val,
                   Type type);

设置空值的方法。

另见:

Hibernate: How to set NULL query-parameter value with HQL?

答案 1 :(得分:8)

对于null对象,请将其指定为:

query.setParameter("name", object, StandardBasicTypes.INTEGER);

StandardBasicTypes.INTEGER已取代Hibernate.INTEGER(等)