为了账号安全,请及时绑定邮箱和手机立即绑定

我可以将 HQL 与 JPA 的 @Query 注释一起使用吗?

我可以将 HQL 与 JPA 的 @Query 注释一起使用吗?

qq_花开花谢_0 2023-08-04 15:01:40
我有两个相同的查询。一个正在运行,entityManager.createQuery()另一个@Query作为PagingAndSortingRepository. entityManager 查询运行正常,但 @Query 注释中的相同查询返回错误。可能是因为@Query注释将查询作为 JPQL 执行,而将entityManager.createQuery()查询作为 HQL 执行?这是两个例子:@Query(不起作用)@Repositorypublic interface UserRepository extends PagingAndSortingRepository<User, UUID> {    @Query("select p.user from Perspective p where p.organisation.id = 'c25c86a0-0d8e-4beb-9ba7-e38d932b8410'")    List<User> findUsers();}could not resolve property: lastname of: org.jembi.appstore.service.entities.Perspective// note: lastname is a property of user, not perspective.entityManager.createQuery(确实有效)    @Autowired    EntityManager entityManager;    @RequestMapping("/query")    @ResponseBody    public void testQuery() {        Query query = entityManager.createQuery("select p.user from Perspective p where p.organisation.id = 'c25c86a0-0d8e-4beb-9ba7-e38d932b8410'");        List<User> users = query.getResultList();        users.forEach(u -> System.out.println(u.getFirstname()));    }
查看完整描述

2 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

这里有几个错误:

  1. 您正在定义@Param("organisationId"),但不在任何地方使用它。

  2. 您正在加入 user: join User u,但从不使用它:与定义没有任何关系Perspective,也没有在where子句中使用。

尝试这个查询:

@Query("select p.user from Perspective p where p.organisation.id = :organisationId")
List<User> findUsers(@Param("organisationId") UUID organisationId, Pageable pageable);


查看完整回答
反对 回复 2023-08-04
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

@Query("select p.user from Perspective p join User u where p.organisation.id = 'c25c86a0-0d8e-4beb-9ba7-e38d932b8410'")
    List<User> findUsers(@Param("organisationId") UUID organisationId, Pageable pageable);
}

我建议你将其重写为:

@Query("select p.user from Perspective p join User u where p.organisation.id = ?1")
    List<User> findUsers(String organisationId);
}

为什么String又不UUID呢?我敢打赌 HQL 不适用于 UUID。+ UUID 可以放入字符串中。
为什么我删除了 Pageable?我在您的查询中找不到您使用第二个参数 [Pageable] 的位置。


查看完整回答
反对 回复 2023-08-04
  • 2 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信