计算字段和Hibernate

时间:2011-05-03 18:25:36

标签: java hibernate

提醒我:如何使用应该保留的计算字段映射Java类?即:

public class PolicyHolder {
    private int height;
    private int weight;
    private boolean smoker;
    private boolean exerciser;

    // getters and setters for those properties omitted for brevity's sake.

    public int getLifeExpectancy() {
        return Utilities.computeBMI(height, weight) + (smoker ? 0 : 20) + (exerciser ?20 : 0);
    end;
}

我在getLifeExpectancy()中有Java中的业务逻辑,我有时会用Java调用它。但我也希望该值与PolicyHolder的其余部分一起持续存在。如何使用Hibernate映射此类?

1 个答案:

答案 0 :(得分:0)

我过去做过这种方式(虽然我不喜欢持久计算值)是让值的getter返回一个字段并让所有影响计算值的其他字段重新计算每当他们改变。这样做你可以告诉hibernate持久化计算字段。

public class PolicyHolder {
    private int height;
    private int weight;
    private boolean smoker;
    private boolean exerciser;
    private lifeExpectancy;  //Tell hibernate to persist this field

    // getters omitted for brevity's sake.

    public void setHeight(int aHeight) {
        height = aHeight;
        computeLifeExpectancy();
    }

    public void setWeight(int aWeight) {
        weight = aWeight;
        computeLifeExpectancy();
    }

    public void setSmoker(boolean aSmoker) {
        smoker = aSmoker;
        computeLifeExpectancy();
    }

    public void setExerciser(boolean anExerciser) {
        exerciser = anExerciser;
        computeLifeExpectancy();
    }

    public int getLifeExpectancy() {
        return lifeExpectancy;
    }

    /**
     * Computes and saves the life expectancy.
     */
    private void computeLifeExpectancy() {
        lifeExpectancy = Utilities.computeBMI(height, weight) + (smoker ? 0 : 20) + (exerciser ?20 : 0);
    }
}

注意:这种方法的一个很大的缺点(在我看来)是所有的设置者现在都有副作用(即,不只是设置他们说他们设置的值)