简体   繁体   English

JPA实体默认值

[英]JPA entity default value

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. 但是,只要JPA加载了实体,就会调用设置器,并在calc中抛出NullPointerException。 Is there anyway to default the values before JPA calls the setters? 无论如何,在JPA调用设置器之前,是否有默认值?

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. 首先,给定您的映射,JPA引擎根本不应该调用设置器,因为您通过将注释放在字段上来选择字段访问。

Second, there is no total field in the code. 其次,代码中没有total字段。

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. 只需让其他类调用calcTotal()即可访问其值。 And rename this method getTotal() . 并重命名此方法getTotal()

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: 如果您确实想存储结果以供重用,请懒惰地对其进行计算,并在修改其中一个操作数时将其重置为null:

public Long getTotal() {
    if (total == null) {
        total = val1 + val2;
    }
    return total;
}

public void setVal1(Long val1) {
    this.val1 = val1;
    this.total = null;
}

public void setVal2(Long val2) {
    this.val2 = val2;
    this.total = null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM