Reputation: 629
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
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
Reputation: 312
Upvotes: 0