且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在一个查询中加载两个不相关的实体(无逗号)[Spring Data JPA]

更新时间:2023-02-09 21:27:46

您可以参考这篇文章以获得更好的解释.

You could refer to this answer and this post for a better explanation.

我经验很少,但是我已经测试了这段代码,它适用于您的特定情况.

I have very little experience, but I've tested this code and it works for your particular case.

在回购文件中(我正在使用Spring boot):

In the repo file (I'm using Spring boot):

@Repository
public interface UserDao extends JpaRepository<User, Long> {

   @Query("select u, p from User u, Post p where u.id =:userId and p.id =:postId")
   List<Object[]> findUserAndPost(@Param("userId") Long userId, @Param("postId") Long postId);

}

然后,要测试是否可行,您可以尝试以下代码:

And then, to test if that worked, you could try this code:

    List<Object[]> results = userDao.findUserAndPost(userId, postId);

    for (int i = 0; i < results.size(); i++) {

        User user = (results.get(i)[0] instanceof User) ? (User) results.get(i)[0] : null;
        Post post = (results.get(i)[1] instanceof Post) ? (Post) results.get(i)[1] : null;

        // Do whatever with user and post...
    }