Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

java - How to return a list of specific type instead of List<Object[]> in Hibernate?

I have tree of classes:

classA {  
      classB b;  
      classC c;
      .....
} 

I have HQL query like this:

SELECT a.field1, b.field2, c.field3, c.field4
FROM a LEFT OUTER JOIN b ON a.id = b.fk
       LEFT OUTER JOIN c ON b.id = c.fk 

This query returns List<Object[]>.

Is it possible to cast the returned data to the following class:

classD {
    Type1 fiedl1;
    Type2 field2;
    Type3 field3;
}

So can casting be made by Hibernate or I need manually do all casting?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are different types of selects in JPA queries. You are currently using Array as a return type, what you need is Construct return type. Here is how to achieve this:

String queryStr =
    "select NEW package.YourDefinedCustomClass(
     a.field1, b.field2, c.field3, c.field4) from a left outer join b 
     on a.id=b.fk left outer join c on b.id=c.fk";

TypedQuery<YourDefinedCustomClass> query =
    em.createQuery(queryStr, YourDefinedCustomClass.class);

List<YourDefinedCustomClass> results = query.getResultList();

Basically there are two things:

  1. Custom class must be your results return type
  2. Custom class must have a constructor which takes result values you define in query string.

Read more on selects in JPA2 queries.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...