org.hibernate.Query.setInteger VS org.hibernate.Query.setParameter(..., ..., Hibernate.INTEGER)

By xngo on June 30, 2019

org.hibernate.Query.setInteger() function doesn't allow your integer to be null whereas org.hibernate.Query.setParameter(..., ..., Hibernate.INTEGER) does.

For example, if you are parsing a file to retrieve the age of a person and then update that age into your database. However, the age is not always written in the file. Therefore, the age is nullable. Here is a code example using setParameter() function to deal with nullable integer:

//...
Query oQuery = session.createSQLQuery("UPDATE Person SET age=:age WHERE id:=id");
oQuery.setInteger("id", id); // id is guaranteed to exist and it is an integer.
oQuery.setParameter("age", age, Hibernate.INTEGER); // age may be null or an integer.
//...
int iRowCnt = oQuery.executeUpdate();
//...

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.