How do I select in specific columns and continue to get a list of the entity and not an array of Object?

2

Having the following class:

  public class Usuario { 
        private Integer id; 
        private Email email;
        private String nome;
        private String sobrenome;
        private String senha;
        private String usuario;
        private List<Grupo> grupos;

        //getters e setters

    }

To do a selct only in the columns name, surname and email I can do this:

SELECT u.nome, u.sobrenome, u.email FROM Usuario u

But in this case, I get back a list of Object [], where each position in the array equals one of the specified columns.

But is there any way to do a select of these and return a User List?

    
asked by anonymous 30.01.2018 / 10:10

2 answers

0

An entity list will not be possible in this model, but what you can do is create a class with the attributes you need and make a builder available with those attributes. See:

public class UsuarioAtributos {
  private String nome;
  private String sobreNome;
  private String email;

public UsuarioAtributos(String nome, String sobreNome, String email) {
    // definir os mapeamentos
}

And in your query you would define it this way:

SELECT new meu.pacote.UsuarioAtributos(u.nome, u.sobreNome, u.email) FROM Usuario u

The return will be a list of UserAttributes and not an Object array anymore.

    
30.01.2018 / 11:07
1

Completing the response of the escapiston, it is possible to do, and it is practically what he already said in his answer:

Assuming your User class is in the following package: br.com.myour system.entities.

Here you can make jpql like this:

SELECT new br.com.meusistema.entidades.Usuario(u.nome, u.sobrenome, u.email) from Usuario u

Notice the new and path of the class.

And it would be necessary to add a matching constructor in the User class:

public class Usuario { 
        private Integer id; 
        private Email email;
        private String nome;
        private String sobrenome;
        private String senha;
        private String usuario;
        private List<Grupo> grupos;

        //construtor padrão
        public Usuario(){}

        //construtor corresponde a busca
        public Usuario(String nome, String sobrenome, String email){        
            this.nome = nome;
            this.sobrenome = sobrenome;
            this.email = email;
        }

        //getters e setters

    }

In short: you need a constructor with the attributes you are looking for in select, and add new and class path in JPQL , so you could get a List as a query return, because for each row of the table will be instantiated an object using the constructor that corresponds to the attributes of the query, if you do not have a corresponding constructor, an exception will be bound by saying that there is no appropriate constructor.     

30.01.2018 / 11:16