是否可以在JPA中执行条件@OneToOne关系

时间:2016-08-31 14:30:15

标签: java jpa relationships

是否可以实现条件@OneToOne关系?

在我正在开发的项目中,我定期对数据进行抽样。多个测量值存储在DB中,但只有最近的测量值反映了设备的实际状态。其余的用于分析。

示例:

@Entity
public class Equipment implements Serializable {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Measurement> measurements

    @OneToOne(fetch = FetchType.EAGAR)
    @ConditionAnnotation( // Note this annotation doesn't exist
        query = "SELECT m FROM Measurement m ORDER BY m.timestamp DESC", 
        maxResults = 1) 
    private Measurement currentState;

}

1 个答案:

答案 0 :(得分:0)

你不能这样做,但我有个主意。单表继承和具有相关测量的第二实体。

@Entity
@Inheritance
@DiscriminatorColumn(name = "TYPE")
public abstract class Equipment implements Serializable {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Measurement> measurements

}

@Entity
@DiscriminatorValue("S")
public class StandardEquipment implements Serializable {

}

@Entity
@DiscriminatorValue("M")
public class EquipmentWithMeasurement implements Serializable {

    @OneToOne(fetch = FetchType.EAGAR)
    private Measurement currentState;

}