简体   繁体   中英

Finding the entity with the highest value in the embedded ID with a custom JPA query

My entity has an composite id consisting of two properties, version and id. I want to find the entity with the highest version. In JPA limit is not possible, how can i restrict my current return to exactly one entity?

@Entity
public class GatewayConfigEntity implements Serializable {
    @EmbeddedId
    private GatewayConfigEntityId gatewayConfigId;
}

@Embeddable
public class GatewayConfigIdEntity implements Serializable {
    private int version;
    private UUID resourceId;
}
@Query("select config from GatewayConfigEntity config where config.deviceId=:deviceId order by config.gatewayConfigId.version desc")
Set<GatewayConfigEntity> findLatestGatewayConfigForDevice(UUID deviceId);
@Query("select config from GatewayConfigEntity config where config.deviceId=:deviceId order by config.gatewayConfigId.version desc")
Set<GatewayConfigEntity> findLatestGatewayConfigForDevice(UUID deviceId, Pageable page);

you invoke the previous query requesting the first page with only one element per page

Set<GatewayConfigEntity> latestGateways = repository.findLatestGatewayConfigForDevice(deviceId, PageRequest.of(0,1));
GatewayConfigEntity latestGateway = latestGateways.isEmpty() ? null : latestGateways.iterator().next();

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