Java使用Hibernate createQuery如何返回过滤后的ScriptInfo对象
修正方案
首先你现有代码的查询语法存在错误,需要先修正再补充返回逻辑:
- 你调用的
createQuery对应HQL查询接口,语法要求写实体类名和实体属性名,不能直接写数据库表名,关联查询语法也要调整;如果你确实要写原生SQL语句,需要调用createNativeQuery方法,同时指定结果类映射。 - 获取查询结果直接调用对应方法即可,单条结果用
getSingleResult(),多条结果用getResultList(),根据你的业务场景选择即可。
修正后完整代码(HQL版本,假设ScriptInfo实体已配置Sprint关联属性)
public ScriptInfo findByForeignKey(int id) { Session currentSession = entityManager.unwrap(Session.class); // ScriptInfo、sprint对应你的实体类名、实体关联属性名,和你本地实体配置保持一致即可 Query<ScriptInfo> theQuery = currentSession.createQuery( "select s from ScriptInfo s join s.sprint sp where sp.id = :idSprint", ScriptInfo.class ); theQuery.setParameter("idSprint", id); // 直接获取单条结果返回 return theQuery.getSingleResult(); }
如果你坚持用原生SQL写法,调整如下:
public ScriptInfo findByForeignKey(int id) { Session currentSession = entityManager.unwrap(Session.class); // 原生SQL调用createNativeQuery,同时指定结果映射类 Query<ScriptInfo> theQuery = currentSession.createNativeQuery( "select s.* from SCRIPT_INF s join SPRINT sp on s.FK_ID_SPRINT = sp.ID_SPRINT where s.FK_ID_SPRINT = :idSprint", ScriptInfo.class ); theQuery.setParameter("idSprint", id); return theQuery.getSingleResult(); }
注意:如果查询可能不存在匹配结果,建议捕获
NoResultException异常,根据业务需求返回null或者做其他异常处理,避免程序直接报错。
内容的提问来源于stack exchange,提问作者Maralde
相关产品推荐
相关产品推荐

