Multiple query with JOIN FETCH command using JPQL

Asked

Viewed 18 times

0

I own the following entity in my application:

@Entity
public class Produto implements Entidade{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String descricao;
    private BigDecimal preco;

    @ManyToMany(fetch = FetchType.LAZY)
    private List<Categoria> categorias = new ArrayList<>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "produto")
    private List<Avaliacao> avaliacoes = new ArrayList<>();

    public Produto() {
    }

    public Produto(String nome, String descricao, BigDecimal preco, List<Categoria> categorias) {
        this.nome = nome;
        this.descricao = descricao;
        this.preco = preco;
        this.categorias = categorias;
    }

    public Long getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public BigDecimal getPreco() {
        return preco;
    }

    public void setPreco(BigDecimal preco) {
        this.preco = preco;
    }

    public List<Categoria> getCategorias() {
        return categorias;
    }

    public List<Avaliacao> getAvaliacoes() {
        return Collections.unmodifiableList(avaliacoes);
    }

    public void addAvaliacao(Avaliacao avaliacao) {
        this.avaliacoes.add(avaliacao);
    }

I would like to perform a single SQL query in Spring Data with LEFT JOIN FECTH using the two properties with @Tomany relationships in the entity. Example of what I plan to do:

"SELECT p FROM Produto p LEFT JOIN FETCH p.categorias WHERE p.id = :id"
"SELECT p FROM Produto p LEFT JOIN FETCH p.avaliacoes WHERE p.id = :id"

My idea is to combine these two appointments into one. I could do it this way?

"SELECT p FROM Produto p LEFT JOIN FETCH p.categorias LEFT JOIN FETCH p.avaliacoes WHERE p.id = :id "

I did not test this code in my application, because I am traveling and without my PC, so I asked here to advance my side.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.