如何从Hibernate Jpa中的父实体仅获取ChildIds(而不是整个子Object)? [英] How to get only ChildIds(Instead of whole child Object) from parent entity in Hibernate Jpa?

查看:76
本文介绍了如何从Hibernate Jpa中的父实体仅获取ChildIds(而不是整个子Object)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,父母和孩子,有一个关系 @OneToMany .如何从Hibernate JPA的父实体中获取唯一的孩子ID(而不是整个孩子的Object)?

I have two tables, parent and child, having a relation @OneToMany. How to get only child ids (instead of whole child Object) from parent entity in Hibernate JPA?

@Entity
Class Parent{
  @Id
  private Integer id;

  private String agreementId;

  @OneToMany
  List<Child> child
}

@Entity
Class Child{
  @Id
  private Integer id;

  @ManyToOne
  List<Parent> parent;
}

接受的输出: {id:1;AgreementId:"12345";子代:[1,2,3,4]}

使用的数据库是Postgresql

推荐答案

为此,您将需要DTO,这也需要您手动将结果展平.我认为这是 Blaze-Persistence实体视图的完美用例

You will need a DTO for this which requires that you also flatten the result manually. I think this is a perfect use case for Blaze-Persistence Entity Views.

我创建了该库,以允许在JPA模型与自定义接口或抽象类定义的模型之间轻松进行映射,例如类固醇上的Spring Data Projections.这个想法是,您可以按自己喜欢的方式定义目标结构(域模型),并通过JPQL表达式将属性(获取器)映射到实体模型.

I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.

针对您的用例的DTO模型可能与Blaze-Persistence Entity-Views相似,如下所示:

A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:

@EntityView(Parent.class)
public interface ParentDto {
    @IdMapping
    Integer getId();
    String getAgreementId();
    @Mapping("children.id")
    Set<Integer> getChild();
}

查询是将实体视图应用于查询的问题,最简单的方法就是按ID查询.

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.

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

Spring Data集成使您可以像使用Spring Data Projections一样使用它:

The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<ParentDto> findAll(Pageable pageable);

最好的是,它只会获取实际必要的状态!

The best part is, it will only fetch the state that is actually necessary!

这篇关于如何从Hibernate Jpa中的父实体仅获取ChildIds(而不是整个子Object)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆