0

Please have a look at the below code.

 String textName=request.getParameter("textName");
 String textadr1=request.getParameter("textadr1");
 String textadr2=request.getParameter("textadr2");
 String textcntry=request.getParameter("textcntry");
 String textregNo=request.getParameter("textregNo");

     AgentContact agentContact=new AgentContact();
     AgentContact agentContact2=new AgentContact();
     Agent agent=new Agent();

     agent.setName(textName);
     agent.setRegistrationNumber(textregNo);
     agent.setDateOfDealStart(textDateDealing);
     agent.setRegistrationDate(textregDate);

     session.save(agent);  
     session.save(agentContact);  
     session.save(agentContact2);          
     session.getTransaction().commit();

In the above code, we get the values from a form, that is why request.getParameter() is used. However, user may or may not fill some fields like name, so the txtName will be empty.

However when this code is executed, I noticed Hibernate added "empty" string to these non specified Strings, instead of entering null. How can I set the code so it enters null values when the text are actually empty?

2
  • does your data field have a default? is it nullable? Commented Feb 12, 2015 at 8:43
  • @djb: It is nullable, yes. No default values, which means if you didn't enter anything it will be NULL Commented Feb 12, 2015 at 8:44

1 Answer 1

2

This is not a Hiberate issue.

See here:

Are empty fields in form of JSP null or ""?

You simply need to check for an empty String and act accordingly:

agent.setName(textName.equals("") ? null : textName);

The above is a somewhat simplistic solution however: what if the user enters a space? You can use methods of Apache Commons StringUtils for more robust checking:

e.g.

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isBlank(java.lang.CharSequence)

agent.setName(StringUtils.isBlank(textName) ? null : textName);

Sign up to request clarification or add additional context in comments.

3 Comments

ah yeah that makes sense. the request params will come in as "", not null.
Thanks. Appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.