Spring Data JPA项目,如何限制嵌套对象的数量@一对多



我正在做一个小型SpringREST API项目。我有两个类,它们表示数据库中的两个表。我在对象中有一个@OneToMany映射,我想从中检索数据。现在我检索所有嵌套对象,但我希望能够通过其int日期戳变量(在我的类中,这是一个声明为"utcs"的epoch(来限制嵌套对象的数量。我天真地以为CrudReposity可以帮助我,但现在我明白我错了。我希望能够在我的存储库中做的事情是这样的:

@Repository
public interface TypeRepository extends CrudRepository<Type, Integer> {
List<Type> findByDataUtcsGreaterThan(int utcs);
}

这就是我想要的JSON结构,以及它现在的样子。但是如何限制数据对象的数量?

[
{
"typeKey": "Queue",
"uomId": 1,
"data": [
{
"value": 11,
"utcs": 1605840300
},
{
"value": 15,
"utcs": 1605840360
},
{
"value": 22,
"utcs": 1605840420
}
]
},
{
"typeKey": "Unroutable",
"uomId": 1,
"data": [
{
"value": 196,
"utcs": 1605840300
},
{
"value": 196,
"utcs": 1605840360
},
{
"value": 196,
"utcs": 1605840420
}
]
}
]

带有嵌套对象@OneToMany 的(Type(对象类

@Entity
@Table(name = "SYSTEMSTATSTYPE")
public class Type {
@Id
@Column(name = "ID")
private int id;
@Column(name = "TYPEKEY")
private String typeKey;
@Column(name = "UOMID")
private int uomId;
@OneToMany(mappedBy = "type", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Data> data = new ArrayList<>();
public Type() {
super();
}
public Type(String typeKey, int uomId) {
this.typeKey = typeKey;
this.uomId = uomId;
}
// Getters and setters
}

(数据(对象类@ManyToOne

@Entity
@Table(name = "SYSTEMSTATSDATA")
public class Data {
@Id
@Column(name = "ID")
private int id;
@Column(name = "VALUE")
private int value;
@Column(name = "UTCS")
private int utcs;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "TYPEID")
private Type type;

public Data() {
super();
}
public Data(int value, int utcs, Type type) {
super();
this.value = value;
this.utcs = utcs;
this.type = type;
}
// Getters and setters
}

我认为不存在直接使用注释的可能性,而且在大多数情况下,使用EAGER获取无论如何都不是一个好主意。我认为您必须使用自定义查询自己构建逻辑,要么只获取2个Data对象(如本文所述https://www.baeldung.com/jpa-limit-query-results),或者一个连接,让您立即将Type和Data组合在一起。

这不是直接可能的。您可以为每个Type对象执行专用的选择查询,也可以使用类似Blaze Persistence Entity Views的东西,它本机支持限制集合元素。

我创建了这个库,以便在JPA模型和自定义接口或抽象类定义模型之间进行简单的映射,比如类固醇上的Spring Data Projections。其思想是,您可以按照自己喜欢的方式定义目标结构(域模型(,并通过JPQL表达式将属性(getter(映射到实体模型。

使用Blaze Persistence实体视图,用例的DTO模型可能如下所示:

@EntityView(Type.class)
public interface TypeDto {
@IdMapping
Integer getId();
String getTypeKey();
int getUomId();
@Limit(limit = "5", order = "utcs DESC")
Set<DataDto> getData();
@EntityView(Data.class)
interface DataDto {
@IdMapping
Integer getId();
int getValue();
int getUtcs();
}
}

查询是将实体视图应用于查询的问题,最简单的是按id进行查询。

TypeDto a = entityViewManager.find(entityManager, TypeDto.class, id);

Spring Data集成使您可以像使用Spring Data Projections一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-数据特征

@Repository
public interface TypeRepository extends CrudRepository<Type, Integer> {
List<TypeDto> findByDataUtcsGreaterThan(int utcs);
}

最新更新