简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM