Search code examples
javahibernatestruts2jpa-2.0pojo

@Column(nullable=false) Not Working


I have started a Struts and Hibernate integration project. I have a column firstname as

@Column(name="FirstName", length=15, nullable=false)
public String getFirstName() {
  return firstname;
}

The firstname is parameter in POJO and its value comes from a Struts form.

Problem is when form is submitted, the empty value of firstname is stored in db.


Solution

  • You can solve the problem easy

    public void setFirstName(String firstName) {
      if (firstName != null && firstName.isEmpty())
        this.firstName = null;
      else
        this.firstName = firstName;
    } 
    

    In computer science, persistence refers to the characteristic of state of a system that outlives (persists more than) the process that created it. This is achieved in practice by storing the state as data in computer data storage.

    The exception for this rule is an empty string which is not affected by the constraint, hence should be fixed somewhere before the data is persisted. Since it's not a problem on the client side, but on the server side the annotation does not check the state of the data which is modified before the session is closed. The SQL exception is thrown in this case.

    It's not a subject to validation. If it's Struts application first time on the server it's validated by Struts. Struts can remove empty parameters from the form but it requires additional configuration settings. Struts can use type conversion to convert empty string properties to null.

    It can use built-in validators using Struts. As I said it's not a question how you handle empty strings coming from the request, but how can you fix it. It doesn't matter what databases treat null values but the problem is only with empty string value stored in the database by hibernate.