java getresultlist,从JPA Query.getResultList()映射到自定义的TO「终于解决」

java getresultlist,从JPA Query.getResultList()映射到自定义的TO「终于解决」Ihaveatablefruitwithfourcolumnsid,name,color,shape.entriesinthetablewouldbe:1,apple,red,round2,banana,yellow,long3,tomato,red,round4,orange,orange,roundNowImadeanentity…

大家好,欢迎来到IT知识分享网。

java getresultlist,从JPA Query.getResultList()映射到自定义的TO「终于解决」

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

entries in the table would be:

1, apple, red, round

2, banana, yellow, long

3, tomato, red, round

4, orange, orange, round

Now I made an entity class Fruit mapped to above table.

@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 obvious, running above query will return 3 rows.

I have a simple TO class FruitSearchTO

class FruitSearchTO

{

String shape;

String name;

//getters/setters here

}

This TO complies with the rows returned by my query.

But in my DAO running something like:

List fruitList = new ArrayList();

fruitList = query.getResultList();

is throwing exception java.lang.ClassCastException: [Ljava.lang.Object; incompatible with FruitSearchTO]

Where am I going wrong and what is the solution to this ?

解决方案

The HQL you’re using will return a List, each element of the List being an array with shape in position 0 and name in position 1.

You can make the HQL return a List using an 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 chapter on HQL, particularly 15.6 The select clause chapter.

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/24470.html

(0)
上一篇 2023-08-21 12:33
下一篇 2023-08-22 15:00

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信