List mapping from JPA Query.getResultList () to custom TO

I have a table fruit with four columns id, name, color, shape.

in the table will be:

1, apple, red, round 2, banana, yellow, long 3, tomato, red, round 4, orange, orange, round 

Now I have created the Fruit entity class mapped to the table above.

 @Entity @Table(name="fruit") public class Fruit implements Serializable { @Id @Column(name="ID") String id; @Column(name="NAME") String name; @Column(name="COLOR") String color; @Column(name="SHAPE") String shape; //getters/setters goes here } 

In my DAO class, the code is:

 String myQuery = "Select f.shape, f.name from Fruit f where f.shape = :shape"; Query query = this.em.createQuery(myQuery); query.setParameter("shape", "round"); 

As is obvious, executing the above query will return 3 rows.

I have a simple TO FruitSearchTO class

 class FruitSearchTO { String shape; String name; //getters/setters here } 

This TO corresponds to the strings returned by my request.

But something like works in my DAO:

 List<FruitSearchTO> fruitList = new ArrayList<FruitSearchTO>(); fruitList = query.getResultList(); 

throws a java.lang.ClassCastException exception: [Ljava.lang.Object; incompatible with FruitSearchTO]

Where am I mistaken and what is the solution to this?

+4
source share
2 answers

The HQL you use will return List<Object[]> , each List element will be an array with shape at position 0 and name at position 1.

You can return the HQL List<FruitSearchTO> with AliasToBeanResultTransformer :

 List fruitList = s.createQuery( "select f.shape as shape, f.name as name from Fruit f where f.shape = :shape;") .setParameter("shape", paramShape) .setResultTransformer( Transformers.aliasToBean(FruitSearchTO.class)) .list(); FruitSearchTOdto = (FruitSearchTO) fruitList .get(0); 

Alternatively, if FruitSearchTO has an appropriate constructor: you can also achieve this with select new FruitSearchTO(f.shape, f.name) .

Take a look at the Hibernate Reference section in HQL, especially the 15.6 Select section .

+6
source

In JPQL, you have a NEW operator that allows you to instantiate an object on the fly, which should not be an entity (as in your case), DTO is not an object).

If you do not want to use the solution for a specific provider, you can use the NEW operator or simply iterate over the received object [] and create your own DTO.

These may be interesting materials for you: How can I avoid creating unnecessary objects? and a little about the NEW operator.

+4
source

All Articles