views:

112

answers:

2

I have an existing JPA (EclipseLink) project where the desired behaviour is that if given a null value in a field for an entity, that null value should not be persisted.

The use case is that we may get several partial updates to these entities from external sources. Those sources may give us a null value, that does not mean "nullify this field" it means "I don't have this value".

Is there an annotation, pattern, or other tool that can be used to automate a null check in the setter OR tell JPA to not persist null values????

I can go through EVERY setter in EVERY entity and add if(val != null) { //set the value } but that is tedious and repetitive.

For example we have:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  this.myColumn = val;
 }
}

I would like to have something that would automatically help like this:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 @DontPersistIfNull
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  this.myColumn = val;
 }
}

OR this:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  //AUTOGENERATED NULL CHECK
  if(val != null) {
   this.myColumn = val;
  }
 }
}
+2  A: 

Not sure if this is the answer you are looking for, but have you checked the Null Object Design Pattern

Mihir Mathuria
It's a similar concept at least. I think I'd want EclipseLink to use that pattern rather than my code. "A column is a NullColumn. When col.persist is called, that invokes NullColumn.persist which causes JPA to not add that column to an INSERT or UPDATE statement.".
Freiheit
+2  A: 

Hibernate validator (and any implementation of javax.validation) has the @NotNull annotation, which will disallow the entity to be persisted if the annotated property is null. I'm not sure of hibernate-validator would work with EclipseLink, but there should be an implementation of javax.validation for EclipseLink as well.

But if you want to block setting nulls - well, then modify the layer that sets the values, rather than the entities themselves.

Bozho
I think this is what I'm hoping for. Can you clarify a bit? If the property is null, does it not persist that proprerty or does it prevent persisting the entire entity?In other words does @NotNull replicate:1. a database constraint where a column cannot be nullOR2. not putting a null property into an UPDATE or INSERT statement
Freiheit
the constraint is at persistence provider level and the entity itself is not persisted at all.
Bozho