[英]Implementing complex MAX function in Spring Boot/JPA query language
Spring 在此处启动,使用 JPA/Hibernate 和CrudRepository
impls 来管理我的数据库表的持久性。
我有以下 MySQL 表:
CREATE TABLE IF NOT EXISTS price_scarcity_configs (
price_scarcity_config_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
price_scarcity_config_ref_id VARCHAR(36) NOT NULL,
price_scarcity_config_version BIGINT NOT NULL,
price_scarcity_config_updated_on DATETIME NOT NULL,
price_scarcity_config_fizz INTEGER NOT NULL,
CONSTRAINT pk_price_scarcity_configs PRIMARY KEY (price_scarcity_config_id),
CONSTRAINT uc_price_scarcity_configs_ref_id_and_version UNIQUE (price_scarcity_config_ref_id, price_scarcity_config_version)
);
这些记录将被版本化,“相同”记录的不同版本将共享相同的price_scarcity_config_ref_id
。 因此,2+ 条记录可以具有相同的price_scarcity_config_ref_id
,但会有两个不同的版本。
我还在使用以下 JPA/Hibernate 实体来 model 它:
// Uses Lombok annotations to generate getters/setters, etc.
@MappedSuperclass
@Data
@EqualsAndHashCode(callSuper=false)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String refId;
}
@Entity
@Table(name = "price_scarcity_configs")
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "price_scarcity_config_id")),
@AttributeOverride(name = "refId", column = @Column(name = "price_scarcity_config_ref_id"))
})
@Data
@EqualsAndHashCode(callSuper=false)
public class PriceScarcityConfiguration extends BaseEntity {
@Column(name = "price_scarcity_config_version")
private Long version;
@Column(name = "price_scarcity_config_updated_on")
private Date updatedOn;
@Column(name = "price_scarcity_config_fizz")
private Integer fizz;
}
我现在正在尝试编写PriceScarcityConfigurationRepository
并需要一个相当复杂的查询。 给定一个refId
,我需要找到与该 ref id 匹配并且具有最高/最大版本号的记录。 执行此操作的原始 SQL 查询是:
select
*
from
price_scarcity_configs pcs
inner join
(
SELECT
price_scarcity_config_ref_id,
MAX(price_scarcity_config_version) as max_ver
FROM
price_scarcity_configs
group by
price_scarcity_config_ref_id
) t
on
t.price_scarcity_config_ref_id = pcs.price_scarcity_config_ref_id
and
t.max_ver = pcs.price_scarcity_config_version;
给定我的存储库并使用 JPA/Hibernate 的内置查询语言/annos,我该如何实现这个查询?
public interface PriceScarcityConfigurationRepository extends CrudRepository<PriceScarcityConfiguration,Long> {
@Query("FROM PriceScarcityConfiguration WHERE ??? HOW TO IMPLEMENT THE ABOVE QUERY HERE ???")
PriceSheetConfiguration fetchLatestVersionByRefId(@Param("refId") String refId);
}
您可以改用以下查询并使用setMaxResults(1)
FROM PriceScarcityConfiguration p WHERE p.refId = :refId ORDER BY p.version DESC
或者干脆使用 Spring 数据表示法
List<PriceSheetConfiguration> findFirstByRefIdOrderByVersionDesc(String refId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.