在实体类

时间:2017-01-07 17:18:45

标签: java hibernate jpa hql

在这种情况下,而不是完成选择对象,决定只对选择语句。所以生成的查询将会更少。

一旦结果出现,我想回到原始值并将它们返回到调用方法。

请建议任何其他有效方法。

      public class Student {
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            private Integer id;

            @Column(name="enroll_id")
            private String enrollmentId;

            public Student(Integer id, String enrollmentId) {
             super();
             this.id = id;
             this.enrollmentId = enrollmentId;
             }
               // source code continues
            }

     public List<Student> getStudentList(){

        Query multipleSelect=em.createQuery("select student.id,student.enrollmentId from Student as student");

        List<Object[]> studentList=multipleSelect.getResultList();

        List<Student> studentArrayList=new ArrayList<Student>();

        for(Object[] list:studentList){
            Integer id=((Integer)list[0]);
            String eId=((String)list[1]);
            studentArrayList.add(new Student(id, eId));
        }

        return studentArrayList;
    }

2 个答案:

答案 0 :(得分:1)

如果您要求一种方法来避免从resultList转换每一行并且必须手动创建Student对象,那么请尝试使用&#34; JPQL Constructor Expressions&#34;

您选择的查询可以修改为:

"select NEW com.FullyQualifiedName.Student(student.id,student.enrollmentId) from Student as student"

并直接接受查询结果

 List<Student> studentList=multipleSelect.getResultList();

或简单地说:

public List<Student> getStudentList(){
    return em.createQuery("select NEW com.FullyQualifiedName.Student(student.id,student.enrollmentId) from Student as student").getResultList();
}

注意:

  1. 确保使用完全限定名称调用Student构造函数。
  2. 不要将JPQL与createNativeQuery一起使用。

答案 1 :(得分:1)

如果您希望查询的输出是Student类型,那么您必须以不同的方式创建查询,即

TypedQuery<Student> multipleSelect=em.createQuery("select NEW your_package.Student(student.id,student.enrollmentId) from Student as student"
                                                 , Student.class);

List<Student> students = multipleSelect.getResultList();

但是,这不是一个好方法,因为方法的返回类型会表明它返回一个完全填充的Student对象。此外,您必须为每个组合制作构造函数。我宁愿建议你拿一张地图,即,

TypedQuery<Map> multipleSelect=em.createQuery("select NEW map(student.id as id,student.enrollmentId as eid) from Student as student"
                                              , Map.class);
List<Map> students = multipleSelect.getResultList();

这将返回一个地图,其中密钥为"id",值为学生的实际ID。