在jpa中使用联合查询,关于返回值类型的问题,一直不知该怎么写,今天终于找到了解决的办法,记录一下
ArticleVoteRepository.java:
@RepositoryRestResource(path = "vote")
public interface ArticleVoteRepository extends JpaRepository<ArticleVote, Integer> {
@Query(nativeQuery = true, value = "select DISTINCT v.id,v.title,v.count,case when vu.user_id is null then 'false' else 'true' end as flag from table1 v left join table2 vu on v.id = vu.vote_id and vu.user_id=:user order by v.id desc")
public List<Object> findVoteList(@Param("user") Integer user);
}
在控制器中:
@Controller
@RequestMapping(path = "api")
public class MainController {
@Autowired
private ArticleVoteRepository voteRepository; @RequestMapping(path = "/getVoteList", method = RequestMethod.GET)
public @ResponseBody List<Object> getVoteList(@RequestParam Integer user) {
ArticleVoteTreeUtil voteUtil = new ArticleVoteTreeUtil();
return voteUtil.voteListTest(voteRepository, user);
}
}
在业务层中:
ArticleVoteTreeUtil.java
public List<Object> voteListTest(ArticleVoteRepository voteRepository, Integer userId) {
this.voteRepository = voteRepository;
List<Object> result = voteRepository.findVoteList(userId);
for (Object row : result) {
Object[] rowArray = (Object[]) row;
Map<String, Object> mapArr = new HashMap<String, Object>();
mapArr.put("id", rowArray[0]);
mapArr.put("title", rowArray[1]);
mapArr.put("count", rowArray[2]);
mapArr.put("flag", rowArray[3]);
list.add(mapArr);
}
return list;
}