简体   繁体   中英

Is it possible to do a conditional @OneToOne relationship in JPA

Is it at all possible to implement a conditional @OneToOne relationship ?

In the project I am developing, I am sampling data on a regular basis. Several Measurements are stored in the DB, but only the most recent reflects the actual state of the equipment. The rest are used for analysis.

Example :

@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;

}

You can not do this, but i have an idea. Single-table inheritence and second entity with related Measurement.

@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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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