How to return an object type instead of List <Object []> to sleep mode?

I have a class tree:

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

I have an hql request, for example:

  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 a List. Is it possible to use sleep mode, for example,

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

therefore, will the cast be done in sleep mode or do you need to manually perform all casting? Thanks.

+7
source share
4 answers

There are various types of selections in JPA queries. You are currently using Array as the return type, you need the Construct return type. Here's how to do it:

 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(); 

There are basically two things:

  • Custom class must be a return type of results
  • A custom class must have a constructor that accepts the result values ​​that you specify in the query string.

Learn more about selecting in JPA2 queries.

+22
source

You can use TypedQuery

 TypedQuery<ClassA> q = em.createQuery("select a from a left outer join b on a.id=b.fk left outer join c on b.id=c.fk", ClassA.class); List<ClassA> res = q.getResultList(); 
+2
source

If you are really sure that you can perform standard casts.

  List<classD> newlist = ...; for(Object o : list){ newlist.add((classD) o); } 

Be careful with this though

So yes. Hand casting. (note: with arrays (you can directly overlay))

+1
source

I had the same problem .. I wrote this request

 Query sqlquery = session.createQuery("select c.courseName,f.facultyID,f.facultyName,f.facultyEmailID,f.facultyContactNo,s.subjectName from com.bean.CourseBean as c,com.bean.FacultyBean as f,com.bean.Faculty_SubjectBean as fs,com.bean.SubjectBean as s where f.facultyID=fs.facultyBean.facultyID AND s.subjectID=fs.subjectBean.subjectID AND c.courseID=f.courseBean.courseID AND collegeid=1"); 

and I returned the list of objects to the servlet that I wrote,

java.util.List objList = objFacultyService.listFaculty_sql (1);

 java.util.List<Temp> objtemp = new ArrayList<Temp>() ; for (Object[] objects : objList) { Temp temp = new Temp(); temp.setFacultyEmailID(objects[3].toString()); temp.setCourseName(objects[0].toString()); if(objects[4]==null) { temp.setFacultyContactNo(1); } else { temp.setFacultyContactNo(Long.parseLong(objects[4].toString())); } temp.setFacultyID(Long.parseLong(objects[1].toString())); temp.setFacultyName(objects[2].toString()); temp.setSubjectName(objects[5].toString()); objtemp.add(temp); } 
0
source

All Articles