gpt4 book ai didi

java - JPA CriteriaQuery 查询每个实体的最新数据

转载 作者:行者123 更新时间:2023-11-30 05:56:05 24 4
gpt4 key购买 nike

我有一个使用 SpringBoot 1.5.9 的项目(无法更改版本)。

我有这些实体:

@Entity
@Table(name = "data")
public class DataEntity extends Timestampable {

@Column(name = "value")
private String value;

@Column(name = "data_timestamp")
private ZonedDateTime dataTimestamp;

@ManyToOne
@JoinColumn
private DataTypeEntity type;

@ManyToOne
@JoinColumn
private AssetEntity asset;
}

@Entity
@Table(name = "data_type")
public class DataTypeEntity extends Timestampable {

@Column(name = "name", unique = true)
private String name;

...
}

我有这个有效的 SQL 查询(在 PostgreSQL 下),用于检索每个 Assets 的最新数据 ( source ):

SELECT * FROM data d1
JOIN (
SELECT max(data_timestamp) as newest, asset_id FROM data
GROUP BY asset_id
) d2
ON d1.data_timestamp = d2.newest AND d1.asset_id = d2.asset_id
WHERE d1.type_id IN (
SELECT id FROM data_type
WHERE name = 'ELECTRICITY_CONSUMPTION'
);

我想将此查询转换为 JPA CriteriaQuery。有没有办法做到这一点,或者我是否需要在特定实体上使用 @SubSelect 注释?

感谢您阅读本文!

(丑陋的)解决方案

我最终使用了带有 SubSelect 的数据库 View 。我已将 DataEntity 分成 2 个实体:

  1. 操纵数据的人
  2. 另一个是 View ,仅用于检索最新数据

基类:

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractDataEntity extends Timestampable {

@Column(name = "value")
protected String value;

...

}

操纵类:

@Entity
@SequenceGenerator(name = "idgen", sequenceName = "data_seq")
@Table(name = "data")
@DiscriminatorValue("DataEntity")
public class DataEntity extends AbstractDataEntity {
@Override
public DataEntity setValue(String value) {
super.setValue(value);
return this;
}

...
}

查看类:

@Entity
@Immutable
@SequenceGenerator(name = "idgen", sequenceName = "view_data_last_seq")
@DiscriminatorValue("LastDataView")
@Subselect(
"SELECT * FROM data d1 " +
"JOIN ( " +
" SELECT max(d.data_timestamp) as newest, d.asset_id, d.type_id FROM data d " +
" WHERE d.parameter_id IS NULL " +
" GROUP BY d.asset_id, d.type_id" +
") d2 " +
"ON d1.data_timestamp = d2.newest " +
" AND d1.asset_id = d2.asset_id " +
" AND d1.type_id = d2.type_id"
)
public class LastDataView extends AbstractDataEntity {
}

即使我觉得这个解决方案很丑,它也可能对其他人有帮助!

最佳答案

JPQL does not support FROMJOIN 上的子查询。仅在 WHEREHAVING 子句中。 Eclipse 链接,starting from 2.4 ,支持 FROM 子句上的子查询。

every Criteria is converted to the JPQL ,不可能使用 Criteria 来完成您想要的操作。

关于java - JPA CriteriaQuery 查询每个实体的最新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53155163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com