Spring Boot 在这里使用 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 实体对其进行建模:
// 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
并需要一个相当复杂的查询。给定 a 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);
}