1

I want to save the result of a query on a List. But when I debug to see the list, it's full of Object[], not a Conta class.

Here is my query and the Conta class.

Query query = em.createQuery("SELECT p.data data, c.nome nomePedido, c.valor, g.nome nomeGarcom FROM Pedidos p\n"
            + "    JOIN Cardapio c ON p.idItem = c.id\n"
            + "    JOIN Garcons g ON p.idGarcon = g.id", Conta.class);
    contaList = query.getResultList();



public class Conta {
private Date data;
private String nomeGarcom;
private String nomePedido;
private float valor;

public Conta(Date data, String nomePedido, float valor, String nomeGarcom) {
    this.data = data;
    this.nomeGarcom = nomeGarcom;
    this.nomePedido = nomePedido;
    this.valor = valor;
}  ... getters and setters
Leandro Souza
  • 69
  • 1
  • 11
  • why not debug it by looking in the JPA providers log? tells you the SQL invoked! –  Sep 24 '18 at 07:01

3 Answers3

2

AFAIK, you can use a constructor expression in JPA, especially since already have a matching constructor:

Query query = em.createQuery("SELECT new com.mine.Conta(p.data, g.nome, c.nome, c.valor) FROM Pedidos p\n" ...
jokster
  • 577
  • 5
  • 14
1

Your Conta class is no Jpa @Entity - that's why it doesn't know how to map the result to your Java Class. Annotate Conta properly, give it a primary key, that's the most straight-forward way.

@Entity
public class Conta {
 @Id
 private long someID;

 @Column
 private float valor;

 @Column
 ... more columns (watch out for your Timestamp, probably needs @Temporal)

....getters and setters
}

As is, you can't use Jpa to save instances of your Conta into the database which is probably one thing you're looking to do later.

Consider this Answer too: JPA : How to convert a native query result set to POJO class collection

Nigel Nop
  • 180
  • 1
  • 6
0

Leandro, can you also please attach the code of getResultList()? From my experience, there are two potential causes. One, your getResultList method has the wrong return type. Two, your query is not working at all.

  • getResultList() is from Java, I didn't wrote it. My query is working. Is returning what I want, but it doesn't create a Conta class. Now I'm trying to cast the Object[] into Conta, but I can't access its values – Leandro Souza Sep 24 '18 at 05:12