在一个查询中加载两个不相关的实体(无逗号)[Spring Data JPA] [英] Loading Two Unrelated Entities (nothing in comman) in One Query [Spring Data JPA]

查看:60
本文介绍了在一个查询中加载两个不相关的实体(无逗号)[Spring Data JPA]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用spring数据jpa将两个不相关的实体(没有共同点)加载到一个查询中?

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

当前代码:

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

这会创建两个sql查询,有什么方法可以做到1个查询.

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

有什么办法做

  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

推荐答案

您可以参考

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

这篇关于在一个查询中加载两个不相关的实体(无逗号)[Spring Data JPA]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆