无法为我的spring data jpa查询使用自定义POJO类。反复失败,但出现以下异常
“ org.hibernate.MappingException:未知实体: com.app.mycompany.AgileCenterServices.entities.ComponentDetailedInfo“ *
试图替换自定义的ComponentDetailedInfo.class并在对EntityManager .createNativeQuery(componentQuery.toString())
的调用期间未提及任何内容,但随后返回的对象列表在查询后无法转换为特定的POJO类。
@Override
public ComponentListResponsePaginated findComponentByProjectId(String projectId, Pageable pageable) {
logger.info(" Inside findComponentByProjectId() API in IssueComponentServiceImpl");
String componentQuery = "select c.*, u.fullname "
+ "from issue_component c "
+ "left join user u on c.component_lead = u.username "
+ "where "
+ "upper(c.project_id) = upper(" + projectId + ")";
List<ComponentDetailedInfo> compList = new ArrayList<ComponentDetailedInfo>();
try {
logger.info(" ************* Printing query ******************************* ");
logger.info(componentQuery.toString());
compList = entityManager.createNativeQuery(componentQuery.toString(), ComponentDetailedInfo.class) .setFirstResult(pageable.getOffset())
.setMaxResults(pageable.getPageSize())
.getResultList();
}
}
也尝试了以下方法
List<? extends Object> objList = null;
objList = entityManager.createNativeQuery(componentQuery.toString()) .setFirstResult(pageable.getOffset())
.setMaxResults(pageable.getPageSize())
.getResultList();
if(objList != null && objList.size() > 0) {
for(Object rec: objList) {
logger.info(" Printing Object ::: " + rec.toString());
compList.add((ComponentDetailedInfo)rec);
}
}
但是compList失败
java.lang.ClassCastException
返回的自定义查询应类型转换为传递给EntityManager .createNativeQuery
的特定类类型。但是,当我将类传递给createNativeQuery()
时,遇到了上面提到的异常。
甚至尝试过完全删除createNativeQuery中的类...
答案 0 :(得分:0)
如果要作为本机查询的结果使用POJO,则必须定义构造函数结果映射。
这是一个示例查询:
Query q = em.createNativeQuery(
"SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
"FROM Customer c " +
"JOIN Orders o ON o.cid = c.id " +
"GROUP BY c.id, c.name",
"CustomerDetailsResult");
这就是您必须添加到实体的映射:
@SqlResultSetMapping(name="CustomerDetailsResult",
classes={
@ConstructorResult(targetClass=com.acme.CustomerDetails.class,
columns={
@ColumnResult(name="id"),
@ColumnResult(name="name"),
@ColumnResult(name="orderCount"),
@ColumnResult(name="avgOrder", type=Double.class)})
})
如果您不喜欢这种方法,可以使用QLRM。在此处了解更多信息:https://github.com/simasch/qlrm