Tony
Tony

Reputation: 3805

How to set Integer parameter as null in Hibernate query?

I've got an entity:

    @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;
        }
        ...

I'm talking about master_id. And this is my DAO method:

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();

    }

Log says:

Request processing failed; nested exception is java.lang.NullPointerException

and puts pointer at this line:

.setInteger("master_id", master_id);

master_id must be null sometimes. So how can I set null?

Upvotes: 21

Views: 40746

Answers (2)

Roger
Roger

Reputation: 131

For a null object, specify it as:

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

StandardBasicTypes.INTEGER replaced Hibernate.INTEGER (etc)

Upvotes: 13

BatScream
BatScream

Reputation: 19700

If you check the documentation of the Query class, setInteger() method,

Query setInteger(String name,int val)

It takes a name and a primitive type int, as parameters.

When you pass a wrapper type Integer, whose value is null, during autoboxing, a null pointer Exception occurs.

For example:

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

You could use

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

method to set null values.

See Also:

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

Upvotes: 26

Related Questions