亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在一個查詢中加載兩個不相關的實體

在一個查詢中加載兩個不相關的實體

慕妹3146593 2021-06-29 09:57:44
如何使用 spring 數據 jpa 在一個查詢中加載兩個不相關的實體,沒有共同點?當前代碼: User user = userRepo.findOne(userId);     Post post = postRepo.findOne(postId);這創建了兩個sql查詢有什么辦法可以做到1個查詢。有沒有辦法這樣做  Object[] userAndPost = someRepo.findUserAndPost(userId, postId);請注意 user 和 post 都是不相關的,并且沒有可以進行 join 的公共列。
查看完整描述

1 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

你可以參考這個答案和這篇文章以獲得更好的解釋。


我的經驗很少,但我已經測試了這段代碼,它適用于您的特定情況。


在 repo 文件中(我使用的是 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);


}

然后,要測試它是否有效,您可以嘗試以下代碼:


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

    }


查看完整回答
反對 回復 2021-07-07
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號