I have an entity with default values and a calculated field as follow:
public class Target{
@Transient
public Long total;
@Min(0)
@Column(columnDefinition="default 0")
public Long val1 = 0L;
@Min(0)
@Column(columnDefinition="default 0")
public Long val2 = 0L;
public Target() {
this.total = Long.valueOf(0L);
this.val1 = Long.valueOf(0L);
this.val2 = Long.valueOf(0L);
}
public Long calcTotal() {
return val1 + val2 ;
}
public void setVal1(Long val) {
this.val1 = checkNotNull(val);
total = calcTotal();
}
public void setVal2(Long val) {
this.val2 = checkNotNull(val);
total = calcTotal();
}
}
However whenever the entity is loaded by JPA, the setters are called and a NullPointerException is thrown in calc.
Is there anyway to default the values before JPA calls the setters?
First of all, given your mapping, the JPA engine should not call the setters at all, because you chose field access by placing the annotations on the field.
Second, there is no
totalfield in the code.Third, this field should not exist at all, since it can be computed from two other fields. Just let other classes call
calcTotal()to access its value. And rename this methodgetTotal().Oh, and the fields should be private, not public.
If you really want to store the result for reuse, then compute it lazily, and reset it to null when one of the operands is modified: