Example Criteria Hibernate Multiple Join/Table SQL
Asked Answered
A

1

5

I have this SQL query

select pr.*,p.id, cf.nome, p.valor_total as "valor total", f.descricao as "forma de pagamento", t.descricao as "tipo de pagamento", s.descricao as "Status" from pedido p
    left join cliente c on c.id = p.id_cliente
    left join cliente_pessoa_fisica cf on cf.id_cliente = c.id
    left join forma_pagamento f on f.id = p.id_forma_pagamento
    left join tipo_pagamento t on t.id = p.id_tipo_pagamento
    left join status_pedido s on s.id = p.id_status_pedido
    left join itempedido itp on itp.id_pedido = p.id
    left join produto pr on pr.id = itp.id_produto

How I can make a Criteria Hibernate SQL using this query?

Automatic answered 12/12, 2013 at 13:24 Comment(1)
What you have tried so far?Means
B
7

Here's my best shot, names of the classes might be different

    CriteriaBuilder qb = entityMan.getCriteriaBuilder();
    CriteriaQuery<Pedido> criteriaQuery = qb.createQuery(Pedido.class);
    Root<Pedido> root = criteriaQuery.from(Pedido.class);

    /**
    * if the Cliente is a list you should use ListJoin instead of Join so it's ListJoin<Pedido, Cliente>
    *if you don't have metadata you can use root.join(root.get("id_cliente")).
    */
    Join<Pedido, Cliente> cliente = root.join(Pedido_.id_cliente, JoinType.LEFT); 
    Join<Cliente, ClientePessoaFisica> clientePessoaFisica = cliente.join(Cliente_.id, JoinType.LEFT);//or if you don't have metadata you can use root.join(cliente.get("id_cliente"))
    Join<Pedido, FormaPagamento> formaPagamento = root.join(Pedido_.id_forma_pagamento, JoinType.LEFT); //or if you don't have metadata you can use root.join(root.get("id_forma_pagamento"))
    Join<Pedido, TipoPagamento> tipoPagamento = root.join(Pedido_.id_tipo_pagamento, JoinType.LEFT);//or if you don't have metadata you can use root.join(root.get("id_tipo_pagamento"))
    Join<Pedido, StatusPedido> statusPedido = root.join(Pedido_.id_status_pedido, JoinType.LEFT);//or if you don't have metadata you can use root.join(root.get("id_status_pedido"))
    Join<Pedido, Itempedido> itempedido = root.join(Pedido_.id, JoinType.LEFT);//or if you don't have metadata you can use root.join(root.get("id"))
    Join<Itempedido, Produto> produto = itempedido.join(Itempedido_.id_produto, JoinType.LEFT);//or if you don't have metadata you can use root.join(itempedido.get("id_produto"))

    /**
    * Here you can select what ever you want, here's an example and you can complete it yourself :)
    * But I would remove this line and select the object itself Pedido
    * Now it depends on you FetchType of the relationships, you might need fetch join
    */
    criteriaQuery.multiselect(root.get("id"), root.get("valor_total"), formaPagamento.get("descricao"));

    TypedQuery<Pedido> query = entityMan.createQuery(criteriaQuery);
    return query.getResultList();
Backside answered 12/12, 2013 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.