Ishan Garg
Ishan Garg

Reputation: 629

How to get only ChildIds(Instead of whole child Object) from parent entity in Hibernate Jpa?

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;
}

Output Excepted: { id: 1; agreementId:"12345"; child:[1,2,3,4] }

DataBase Used is Postgresql

Upvotes: 0

Views: 1543

Answers (2)

Christian Beikov
Christian Beikov

Reputation: 16452

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.

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.

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();
}

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);

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!

Upvotes: 2

Dattq2303
Dattq2303

Reputation: 312

  • According to what i know, the answer is you can't. Hibernate mapping by entity so you always have the whole child object.
  • I don't know what you want to do but i think you should just get the whole child list object then modify it (maybe by a stream.map() function) to become a list childId as you want

Upvotes: 0

Related Questions