Loading Two Unrelated Entities (nothing in comman)

2019-06-09 21:34发布

问题:

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