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

我有两个相同的查询。一个正在运行,entityManager.createQuery()另一个@Query作为PagingAndSortingRepository. entityManager 查询运行正常,但 @Query 注释中的相同查询返回错误。


可能是因为@Query注释将查询作为 JPQL 执行,而将entityManager.createQuery()查询作为 HQL 执行?


这是两个例子:


@Query(不起作用)


@Repository

public 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()));

    }


qq_花开花谢_0
浏览 89回答 2
2回答

UYOU

这里有几个错误:您正在定义@Param("organisationId"),但不在任何地方使用它。您正在加入 user:&nbsp;join User u,但从不使用它:与定义没有任何关系Perspective,也没有在where子句中使用。尝试这个查询:@Query("select&nbsp;p.user&nbsp;from&nbsp;Perspective&nbsp;p&nbsp;where&nbsp;p.organisation.id&nbsp;=&nbsp;:organisationId") List<User>&nbsp;findUsers(@Param("organisationId")&nbsp;UUID&nbsp;organisationId,&nbsp;Pageable&nbsp;pageable);

一只萌萌小番薯

@Query("select&nbsp;p.user&nbsp;from&nbsp;Perspective&nbsp;p&nbsp;join&nbsp;User&nbsp;u&nbsp;where&nbsp;p.organisation.id&nbsp;=&nbsp;'c25c86a0-0d8e-4beb-9ba7-e38d932b8410'") &nbsp;&nbsp;&nbsp;&nbsp;List<User>&nbsp;findUsers(@Param("organisationId")&nbsp;UUID&nbsp;organisationId,&nbsp;Pageable&nbsp;pageable); }我建议你将其重写为:@Query("select&nbsp;p.user&nbsp;from&nbsp;Perspective&nbsp;p&nbsp;join&nbsp;User&nbsp;u&nbsp;where&nbsp;p.organisation.id&nbsp;=&nbsp;?1") &nbsp;&nbsp;&nbsp;&nbsp;List<User>&nbsp;findUsers(String&nbsp;organisationId); }为什么String又不UUID呢?我敢打赌 HQL 不适用于 UUID。+ UUID 可以放入字符串中。为什么我删除了 Pageable?我在您的查询中找不到您使用第二个参数 [Pageable] 的位置。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java