1 回答

TA貢獻1776條經(jīng)驗 獲得超12個贊
你可以參考這個答案和這篇文章以獲得更好的解釋。
我的經(jīng)驗很少,但我已經(jīng)測試了這段代碼,它適用于您的特定情況。
在 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...
}
添加回答
舉報