ActiveWeb:在模板中调用时,模型设置器/获取器不起作用

时间:2018-09-24 08:37:01

标签: javalite activeweb

在使用旧数据库时,有时无法使用belongs_to批注正确地建立关系。在这种情况下,我尝试使用以下访问器方法定义指向另一个Model类的属性:

@Table("INTERVENTION")
@IdName("ITV_ID")
public class Intervention extends Model {
  private InterventionModel interventionModel;

    public InterventionModel getInterventionModel() {
        return interventionModel;
    }

    public void setInterventionModel(InterventionModel interventionModel) {
        this.interventionModel = interventionModel;
    }
}

我在服务类中加载并设置InterventionModel时没有出现以下问题(intervention实例存在):

private void loadInterventionModel(final Intervention intervention) {
        final InterventionModel model = InterventionModel.findById(intervention.getLongId());
        intervention.setInterventionModel(model);
    }

问题是,当我尝试评估FreeMarker模板中的InterventionModel属性时,它不起作用:

"item_code:": ${intervention.intervention_model.imo_internal_code}

这是刷新的错误:

FreeMarker template error:
An error has occurred when reading existing sub-variable "intervention_model"; see cause exception! The type of the containing value was: extended_hash+string (app.models.Intervention wrapped into f.e.b.StringModel)

Caused by: java.lang.IllegalArgumentException: Attribute: 'intervention_model' is not defined in model: 'class app.models.Intervention.

我在这里缺少什么,为什么它不能按预期工作? 通常,如果我在模型中声明了带有其访问器(getter和setter)的属性,则可以在模板中通过以下方式访问它:

mymodel.my_attribute

2 个答案:

答案 0 :(得分:0)

我认为,我找到了原因。 似乎在类模型中声明实例变量且此变量不属于模型可用属性(表列)时,应使用snake_case而不是camelCase编写,即不要声明:

public class Intervention extends Model {
...
  private InterventionModel interventionModel;

  public InterventionModel getInterventionModel() {
        return interventionModel;
    }

    public void setInterventionModel(InterventionModel interventionModel) {
        this.interventionModel = interventionModel;
    }

}

使用snake_case版本:

private InterventionModel intervention_model;

public InterventionModel getIntervention_model() {
    return intervention_model;
}

public void setIntervention_model(InterventionModel intervention_model) {
    this.intervention_model = intervention_model;
}

这样,您将能够在模板中像在模型中使用其他变量一样访问它:

"label": "${intervention.intervention_model.imo_product_label}"

一开始,我认为转换是自动完成的。您可以保留camlCase版本,在这种情况下,您也应该在模板中使用它:

"label": "${intervention.interventionModel.imo_product_label}"

希望这会有所帮助。

答案 1 :(得分:0)

如果您的班级InterventionModel指向旧表,则可以执行以下操作:

@Table("INTERVENTION")
@IdName("ITV_ID")
public class Intervention extends Model {
  private InterventionModel interventionModel;

    public InterventionModel getInterventionModel() {
        return interventionModel;
    }

    public void setInterventionModel(InterventionModel interventionModel) {
        this.interventionModel = interventionModel;
    }

    Object getImoProductLabel(){
        return interventionModel.imo_product_label();
    }
}

然后在模板中:

"label": "${intervention.imoProductLabel}"

这样,您不仅将为模板构建方法,还将为代码中的其他位置构建方法,并提取掉旧代码。

相关问题