Chitransh Agarwal
Chitransh Agarwal

Reputation: 83

Hibernate: Limit result size of child objects

I've got a parent entity which has many child objects, most of which are collections. See below.

@Entity
@Table(name = "A")
public class A {

    @Id
    @Column(name = "ID")
    private long id;

    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name = "A_ID", nullable = false)
    private Set<B> setB;

    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name = "A_ID", nullable = false)
    private Set<C> setC;

    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name = "A_ID", nullable = false)
    private Set<D> setD;

    // Skipping more collections as they are not needed for the example
    // Standard getters and setters
    
}

Now classes B, C and D have A_ID and 5 more String columns. Please consider them B1,B2,B3,B4,B5 and so on. I also have a CrudRepository for A

@Repository
public interface ARepository extends CrudRepository<A, Long> {
    Optional<A> findById(Long id);
}

I want to fetch the complete A object with an id but the other child collections that A have (setB, setC, setD) contains approx thousands of rows for each A_ID. I want to put a filter to fetch only first 100 rows for a given A_ID. I have tried putting @Where(clause = "ROWNUM < 101") on the collections but it does not work as in the query the table name gets prefixed to the ROWNUM. I also took a look at Criteria and Criterion but I am unable to find any working solution. Since there are many collection of Objects in the parent class. So using native queries for each object would be too much rework. Can anyone please help me with this. Do comment if you need more information. Thanks

Upvotes: 1

Views: 819

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16430

That's not so easy. You would have to fetch the collections manually or use a library like Blaze-Persistence Entity-Views on top that supports this out of the box. Also see here for a similar question: Hibernate - Limit size of nested collection

In your particular case, this could look like the following:

@EntityView(A.class)
public interface ADto {

    @IdMapping
    long getId();

    @Limit(limit = "100", order = "id asc")
    Set<BDto> getSetB();

    @Limit(limit = "100", order = "id asc")
    Set<C> getSetC();

    @Limit(limit = "100", order = "id asc")
    Set<D> getSetD();
    
}

Upvotes: 1

Related Questions