如何在实体的瞬态字段中从存储过程设置计算字段?

时间:2020-04-10 11:49:44

标签: java spring hibernate jpa

数据库(Firebird)中有一个表,它已映射到Entity。

存储过程与此表一起使用,该表将同时返回表中的字段值和计算出的值。

对于Entity中的此计算值,我创建了一个Transient变量。

我有SqlResultSetMapping,其中写了从存储过程到Entity中字段的对应关系。

问题是没有任何内容写入“瞬态”字段。

是否可以将计算值设置为瞬态场?

@NamedStoredProcedureQuery(
        name = Building.VR,
        procedureName = "VALUATION_RESULTS_VC",
        resultSetMappings = "Mapping",
        parameters = {
            @StoredProcedureParameter(mode = ParameterMode.IN, name = "IP_ID", type = Integer.class),
            @StoredProcedureParameter(mode = ParameterMode.OUT, name = "P_ID", type = Integer.class),
            @StoredProcedureParameter(mode = ParameterMode.OUT, name = "P_CLASS", type = String.class),
            @StoredProcedureParameter(mode = ParameterMode.OUT, name = "P_CRN_VC", type = Double.class)
        }
)
@SqlResultSetMapping(
        name = "Mapping",
        entities = @EntityResult(
                entityClass = Building.class,
                fields = {
                        @FieldResult(name = "id", column = "P_ID"),
                        @FieldResult(name = "name", column = "P_CLASS"),
                        @FieldResult(name = "crn", column = "P_CRN_VC")
                }
                )
)
@Access(AccessType.FIELD)
@Entity
@Table(name = "main_tab")
public class Building extends BaseEntity {
    public static final String VR = "Asset.VR";

    @Transient <-if you remove Transient and create such a real field in the table, then everything works. But this field is calculated and it is not needed in the table.
    private Double crn;

    public Double getCrn() {
        return crn;
    }

    public void setCrn(Double crn) {
        this.crn = crn;
    }
}



@MappedSuperclass
public abstract class BaseEntity {
    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了一种替代解决方案,例如:

在实体类中,使用@column(update=false,insertable=false)定义属性,该属性仍在表中创建一列,但仅作为只读列。使用此列作为派生列可从存储过程中获取。