Multiple joins in HQL Query, duplicate instances of only one object in resulting collection

21 Views Asked by At

So I have following entities in a project I'm working (it's all huge so I will post a simplification):

public class A {
    .
    .
    .
    private String dateKey;
    .
    .
    .
    @ManyToOne
    @JoinColumn(name = "b_key", referencedColumn = "b_key")
    private B b;

    @ManyToOne
    @JoinColumn(name = "c_key", referencedColumn = "c_key")
    private C c;

    @ManyToOne
    @JoinColumn(name = "d_key", referencedColumn = "d_key")
    private D d;

    @ManyToOne
    @JoinColumn(name = "e_key", referencedColumn = "e_key")
    private E e;
}

public class B {
    .
    .
    .
    @OneToMany
    @JoinColumn(name = "b_key", referencedColumn = "b_key")
    private List<B_details> b;

}

public class B_details {
    private Long b_key;

    private String dateKey;

    private boolean valid;

}

public class C {
    //irrelevant fields

}

public class D {
    //irrelevant fields

}

public class E {
    //irrelevant fields
}

The relations between B and B_details is defined as @OneToMany because the details change and differ by date. Then there's this monstrosity of a HQL query:

select a from A a 
inner join fetch a.b b 
join fetch b.b_details
join fetch a.c
join fetch a.d
join fetch a.e
where a.dateKey = :date
and //... more conditions related to c d e fields

I want to focus on the relation between B and B_details. I would expect to get a list of B_details for each B and said collection should contain a number of distinct objects. But what I get instead is B with a collection of B_details where each B_details is exactly the same instance of the same object. The number of elements in the collection is correct but they are all the same, like only the first one was taken and the copied multiple times.

I've read multiple posts and articles and I still can't get where I want to be with the result. Ideally, I wanted to get only one B_details for a B by adding something like join fetch b.b_details bd ON bd.dateKey = :date but I understand it's not allowed as I get errors in type of `with-clause not allowed on fetched associations. This is also a big problem as I wanted to join with a smaller, filtered collection, it's a read-only app.

I haven't worked with HQL or SQL joins too much in the past and I can't wrap my head around the problem I'm facing. In my understanding it should work and I con't understand why of all things, I get these duplicates instead of a collection with unique, true to the fact objects.

Please feel free to ask for more details as these are really huge entities and it would take me ages to provide a full representation and I can't just copy the code 1:1.

0

There are 0 best solutions below