1

I want to use this HQL query in order to select table row value:

String hql = "select e.token, e.name from Terminals e where e.token = ?";
Terminals terminal = entityManager
    .createQuery(hql, Terminals.class)
    .setParameter(0, terminalToken)
    .getSingleResult();

But I get this result:

java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [org.api.entity.Terminals]

What is the proper way to implement this?

YCF_L
  • 49,027
  • 13
  • 75
  • 115
Peter Penzov
  • 7,110
  • 86
  • 300
  • 595

2 Answers2

2

Your query return two Objects token and name and not a Terminals Object.

Instead you can use :

Object[] obj = entityManager
    .createQuery(hql)
    .setParameter(0, terminalToken)
    .getSingleResult();

if(obj != null){
    Terminals terminal = new Terminals((String) obj[0], (String) obj[1]);
}

Or you can create a constructor in Terminals class which hold two fields :

public Terminals(String token, String name){
   this.token = token;
   this.name = name;
}

then change your code to be :

String hql = "select new com.package.Terminals(e.token, e.name) from Terminals e where e.token = ?";
Terminals terminal = entityManager
    .createQuery(hql, Terminals.class)
    .setParameter(0, terminalToken)
    .getSingleResult();
YCF_L
  • 49,027
  • 13
  • 75
  • 115
1

IMO, you should not directly call createQuery to assign to a custom object. And there is a possiblity of returning a list.

Query query = entityManager.createQuery(hql).setParameter(0, "something");<br>
List<Object[]> terminals = query.getResultList();

and retrieve the objects with an index as the ff as an example:

        StudentDto dto = new StudentDto();
        for(Object[] a: std) {
            dto = new StudentDto();
            dto.setId((long) a[0]); //id
            dto.setName(a[1].toString()); //first name
            dto.setPassportNumber(a[2].toString()); //last name
        }
Aman
  • 1,335
  • 8
  • 13