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...
}
添加回答
举报