spring-data-jpa Spring Data Jpa规范中的聚合(计数、求和)和分组

fdx2calv  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(410)

他的家伙,我是一个新的Java,我有点卡住了。如果它可能得到像Map〈状态,整数〉使用规范的人吗?我有类的人和状态,我的业务,使端点返回这些Map的过滤器(性别,年龄)如何工作过滤器我已经了解,但如何不使用 @query 得到Map-不。下面我的类:

@Entity(name = "persons")
@Getter
@Setter
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String id;
    private String name;
    private int age;
    private String sex;
    private Status status;
}

@Getter
public enum Status {
    ONLINE,
    OFFLINE,
    BANNED,
    DELETED;
}

我端点必须返回{ ONLINE:5、离线:17、禁止:2、删除:四个

rjzwgtxy

rjzwgtxy1#

我相信您正在寻找投影:https://www.baeldung.com/spring-data-jpa-projections
Spring Data 允许您使用一个接口来做您所要求的事情,而不需要提供一个实现,这是非常方便的!
假设您有一辆实体汽车:

@Entity
public class Car {

    @Id
    private Long id;

    private String model;

    private String color;

    private int year

    // getters and setters
}

您希望检索颜色和年份。您可以通过以下接口来实现:

public interface ICarProjection {
    String getColor();
    int getYear();
}

确保接口中方法的命名与实体的命名相同,这一点很重要。
在存储库中,您现在可以使用接口来代替完整实体:

public interface CarRepository extends Repository<Car, Long> {
    @Query('xxx')
    List<ICarProjection> getColorAndYear();
}
rxztt3cl

rxztt3cl2#

是的,你可以在实体上获得Map集合,但只有当你使用@ElementCollection连接两个平板电脑时才可以。

@Entity
public class Store {
  @Id
  protected long id;

  @ElementCollection
  @CollectionTable(name = "item_quantity",
        joinColumns = { @JoinColumn(name = "store_id") })
  @MapKeyColumn(name = "item")
  @Column(name = "quantity")
  protected Map<String, Integer> itemQuantityMap = new HashMap<>();

在您的情况下,更好的方法是按流Map结果列表。

List<Person> result = repository.findAll();
var map = result.stream().collect(Collectors.toMap(Person::getStatus, Person ::getSex))

相关问题