Properties and NULL values

In Figure 935, “Database schema mapping instances of hibintro.v1.model.User. ” the primary key uid property's value must not be NULL. This is an immediate consequence of the javax.persistence.Id annotation and the fact that databases don't allow NULL values for key attributes.

The cname property however may be null. Sometimes we want to ensure the corresponding database attributes to be set, at least carrying an empty string value. This can be achieved by adding a javax.persistence.Column (nullable = false) annotation:

Java
package hibintro.v4;
    ...
@Entity public class User {
  ...
   String cname;
   @Column(nullable = false) public String getCname() {
   return cname;
  }
     ...
SQL
CREATE TABLE User (
   uid VARCHAR(255) NOT NULL PRIMARY KEY,
   cname VARCHAR(255) NOT NULL ❶
)

This results in a corresponding database constraint ❶. Attempts to store instances with null values now fail:

Java
package hibintro.v4;
	    ...
	    public class PersistSingleUser {

     em.getTransaction().begin();
     {
        em.persist(new User("goik", "Martin Goik"));
     }
     em.getTransaction().commit();
Log
Exception in thread "main" javax.persistence.PersistenceException: 
  org.hibernate.PropertyValueException: not-null property references a null or transient value : 
hibintro.v4.User.cname
 at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
   ...
 at hibintro.v4.PersistSingleUser.main(PersistSingleUser.java:22)

The database constraint violation causes the JDBC™ driver to throw this exception.