Loading Two Unrelated Entities (nothing in comman) in One Query [Spring Data JPA]

不羁岁月 提交于 2019-12-08 11:08:20

问题


How can two unrelated entities , nothing in common be loaded in one Query using spring data jpa?

Current Code :

 User user = userRepo.findOne(userId);
 Post post = postRepo.findOne(postId);    

This creates two sql query is there any way to do it 1 Query.

Is there any way doing like this

  Object[] userAndPost = someRepo.findUserAndPost(userId, postId);

Please note both user and post are unrelated and have no common column on which join can be done.

Sandeep


回答1:


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.

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...
    }


来源:https://stackoverflow.com/questions/51740660/loading-two-unrelated-entities-nothing-in-comman-in-one-query-spring-data-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!