Returning result from 3 tables using JPA criteria

191 Views Asked by At

I have the following situation:

@Entity
public class Period
{
    String Name;
}

@Entity
public class Bill
{
    Period period;

    @OneToMany(mappedBy = "bill", fetch = FetchType.LAZY)
    private List<Entry> entry = new ArrayList<Entry>(0);
}

@Entity
public class Entry
{
    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "BILL_ID", nullable = false)
    Bill bill;

    String text;

    BigDecimal amount;
}

So what I need is to fetch all the data in a single query, either with the root being the Bill or the Entry using JPA 2.0 criteria (with Hibernate behind). I've read few posts about this problem HERE and HERE and it seems that I can't use subqueries in the result or fetch data two levels deep.

EDIT: To make my problem more clear: When I use Entry as root, I can't fetch Period and when I use Bill as root I can't fetch all other tables in Entry. Also I can't use eager fetch because there are other use cases that need those tables.

Are there any other ways to do this?

Thanks!

1

There are 1 best solutions below

7
On BEST ANSWER

To fetch data from association, you use left join fetch clauses:

select distinct b from Bill b 
left join fetch b.period 
left join fetch b.entry
where b...

or

select distinct e from Entry e 
left join fetch e.bill b 
left join fetch b.period
where e...

Regarding Criteria, its fetch() method returns a Fetch, which itself has a method fetch() returning a Fetch(), which itself has a method fetch() returning a Fetch, etc. So yes, its supports as many levels you want.