Search code examples
javahibernatecriteria-api

Jpa criteria api - create class that connect other class


Let's say I have the following SQL:

select * from table1
inner join table2 on table1.id = table2.table1id;
inner join table3 on table2.id = table3.table2id;
inner join table4 on table3.id = table4.table3id;

and I have Java entities like table1, table2, table3 and table4.

I want to map this query using criteria API. In order to do that I created class Table5 which contains all of fields of all classes.

Then I created a repository with the method:

public List<Table5> getAllTable5 () {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Table5> query = cb.createQuery(Table5.class);
    Root<Table1> root = query.from(Table1.class);

    Join<Table1, Table2> table1Table2Join= root.join(Table1_.TABLE2);
    Join<Table2, Table3> table2Table3Join= root.join(Table2_.TABLE3);
    Join<Table3, Table4> table3Table4Join= root.join(Table3_.TABLE4);

    query.multiselect(
           root.get // all fields
    );

    TypedQuery<Table5> typedQuery = em.createQuery(query);

    return typedQuery.getResultList();
} 

Is it possible to create class like:

class Table5 {
    private Table1 table1;
    private Table2 table2;
    private Table3 table3;
    private Table4 table4;
    
    // getters setters constructors
}

If yes, how should getAllTable5 method look like?


Solution

  • You can either select every table entity, or select just the first one and rely on join fetching.

    public List<Table5> getAllTable5 () {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Table1> query = cb.createQuery(Table1.class);
        Root<Table1> root = query.from(Table1.class);
    
        query.select(root);
    
        TypedQuery<Table1> typedQuery = em.createQuery(query);
        EntityGraph entityGraph = em.createEntityGraph();
        // Apply subgraphs for the associations to fetch
        typedQuery.setHint("javax.persistence.loadgraph", entityGraph);
        List<Table1> list = typedQuery.getResultList();
        List<Table5> table5s = new ArrayList<>(list.size());
        for (Table1 t : list) {
            table5s.add(new Table5(t, t.getTable2(), , t.getTable2().getTable3(), , t.getTable2().getTable3().getTable4());
        }
        return table5s;
    }