Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检索实体的特定字段并将其强制转换为另一个实体_Java_Jpa - Fatal编程技术网

Java 如何检索实体的特定字段并将其强制转换为另一个实体

Java 如何检索实体的特定字段并将其强制转换为另一个实体,java,jpa,Java,Jpa,我有一个用于检索持久化orm中已经定义的实体的特定部分的用例,我希望它是一个包含这些字段的一部分的新实体 我知道对于数据规范化,我应该将这些字段提取到新实体,但不幸的是,这超出了范围。还有许多传统连接器将数据插入这种格式 我想我可以简单地使用新实体的TypedQuery并创建一个命名查询来检索旧实体的特定字段 作为参考,我的示例实体StudentLessons如下所示 String LessonId String LessonName String LessonRegistration Stri

我有一个用于检索持久化orm中已经定义的实体的特定部分的用例,我希望它是一个包含这些字段的一部分的新实体

我知道对于数据规范化,我应该将这些字段提取到新实体,但不幸的是,这超出了范围。还有许多传统连接器将数据插入这种格式

我想我可以简单地使用新实体的TypedQuery并创建一个命名查询来检索旧实体的特定字段

作为参考,我的示例实体
StudentLessons
如下所示

String LessonId
String LessonName
String LessonRegistration
String StudentId
String StudentName
String StudentAge
我已经创建了一个新实体
Student

String StudentId
String StudentName
String StudentAge
我想检索一个LessonId的学生列表,注意这个学生没有被持久化,只用于数据传输

因此,我在
StudentLessons

        <named-query name="StudentLessons.GetStudents">
            <query>SELECT SL.StudentId, SL.StudentName, SL.StudentAge FROM StudentLessons SL WHERE SL.LessonId= :LessonId</query>
        </named-query>

从StudentLessons SL中选择SL.StudentId、SL.StudentName、SL.StudentAge,其中SL.LessonId=:LessonId
然后我创建了一个方法来检索学生列表

    public List<Student> getStudents(Integer LessonId) {
        final EntityManager em = emf.createEntityManager();
        try {
            final TypedQuery<Student> query = em.createNamedQuery("StudentLessons.GetStudents", Student.class);
            query.setParameter("LessonId", LessonId);
            return query.getResultList();
        } finally {
            em.close();
        }
    }
public List getStudents(整数LessonId){
最终EntityManager em=emf.createEntityManager();
试一试{
最终类型dquery query=em.createNamedQuery(“studentclasses.GetStudents”,Student.class);
setParameter(“LessonId”,LessonId);
返回query.getResultList();
}最后{
em.close();
}
}
虽然这成功地检索了课程中的学生列表,但不会将其强制转换为学生。 相反,我得到了一个错误
com.fasterxml.jackson.databind.JsonMappingException:无法将java.lang.String字段com.package.entity.Student.StudentId设置为[Ljava.lang.Object;(通过引用链:java.util.Vector[0]->Object[]StudentId])

我是否可以将查询结果强制转换为预期的实体


注意,在我提供的示例中,实体中只有6个字段,在我的实际项目中,它要复杂得多,这就是为什么我只想传输学生。

您要查找的是JPA结果类。 看

本质上,JPA查询检索JPA实体XML中配置的实体的实例。如果要检索另一个实体,则需要在select子句中显式构造要检索的对象。在您的情况下,这将是:

您需要在Student类中创建相应的构造函数

SELECT NEW Student(SL.StudentId, SL.StudentName, SL.StudentAge)
FROM StudentLessons SL WHERE SL.LessonId= :LessonId