Banns
Banns

Reputation: 596

JPQL - How can I get an extra param inside my entity?

I am new to JPQL and I am trying to get an extra parameter that is not in the entity, but I am not finding how to do it.

Through searched here in the forum I found out that some uses a DTO for it, but I am not knowing how to apply that.

Here is my entity:

@Entity
@Table(name = "person")
public class Person implements Serializable {

    private int id;
    private String name;
    private String email;
    private int age;

...
}

And my JPQL:

SELECT COUNT(a.name) as countOfNames, a FROM Person a WHERE a.name like :name

How can I get the countOfNames result inside of myentity object since it is not a column?

Upvotes: 0

Views: 97

Answers (1)

v.ladynev
v.ladynev

Reputation: 19956

The simplest way is to use a constructor expression

package com.entites

public class PersonDto {

    private Person person;

    private Integer countOfNames;

    public PersonDto(Person person, Integer countOfNames) {
        this.person = person;
        this.countOfNames = countOfNames;
    }

}

select new com.entites.PesronDto(a, count(a.name)) 
  from Person a 
  where a.name like :name

Upvotes: 1

Related Questions