tags:

views:

28

answers:

3

I am new to Java and I am creating an application in JSF and Hibernate.

I have a form which has several input fields but only one field that will be an Integer, Age. The rest of them will be Strings. Age is not a required field so the user can enter it or not but my application should insert null or an empty string into the DB if the field is left blank. I have done error handling if a user manually enters a character other than an number but I want to allow the user to enter nothing and still be able to submit so I allow for an empty string. This is where my problem is. My createUser method that calls a Insert statement on my DB requires an Int, so I figured I could pas NULL and this would work but I am getting a null pointer excpetion when I set the field to null. A snapshot of my code is below.

I have left out all of the other code and just simplified it with just inserting a new user by passing Age.

//inside UserManager.java file
public void createUser(ActionEvent event) {

  String age = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("createAge");

  try {
     //check to make sure that it is not empty
     Integer ageInt = null; 
     if(!age.equals("") ) {
         ageInt = new Integer(age).intValue();
     }

     userDao.createUser(ageInt);
  }
  catch(Exception e) {
      e.fillInStackTrace();
  }
}

//inside UserDao.java file
public void createUser(Integer age) { 
    Session sess = getSessionFactory().openSession();

    try {
        Query.insertUser = session.createSQLQuery("CALL inser_user(:age)");
        insertUser.setInteger("age", age);
        insertUser.executeUpdate();
    }
    catch(HibernateException e) {
         throw new HibernateException(e);
    } finally {
         session.close();
    }
}
+2  A: 

because the code here is trying to setInteger with a null

insertUser.setInteger("age", age);

I would suggest passing "0" to indicate no age was provided? This way you can save a value in the db and know it actually has meaning

or

if ( age == null ) {
   insertUser.setParameter("age", null);
} else {
   insertUser.setInteger("age", age);
}
Aaron Saunders
there is no .setNull() method on a Query object at least its not showing up in my list of methods
NewToJSF
updated answer to reflect input from @Ryan
Aaron Saunders
A: 

If the field is null use the setNull() method rather than setInteger().

djna
I don't see a setNull() method on a Query object.
NewToJSF
maybe use java.sql.PreparedStatement which does?
djna
A: 

Can you use Aaron's solution, but use:

insertUser.setParameter("age", null);
Ryan P.