Spring Data JPA 实现联表查询

Spring Data JPA在简单的单表查询上确实非常方便,不过如果需要联表查询就会变得复杂这里写一种联表查询的方法:通过 EntityManager

@RestController
@RequestMapping(value = "/friend")
public class FriendControl {

    // 采用EntityManager进行联表查询
    @Resource
    EntityManager entityManager;

    // 获取个人的好友列表 getMyFriends
    // friendId 好友的userId 传入为查询某个好友详情
    @RequestMapping(value = "getMyFriends",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result getMyFriends(
            @RequestParam(value = "friendId",required = false)String friendId,
            HttpServletRequest request
    ){
        Integer userId = 1;
        // 这里需要我们写原生sql去进行查询
        String sql="Select u.* from user u "
                + "left join friend f on f.friend_id=u.user_id "
                + "where f.user_id = "+userId;
		// 拼接sql进行条件查询
        if(!(friendId==null||"".equals(friendId))){
            sql += " and f.friend_id = " + friendId;
        }

        List> resultList = entityManager.createNativeQuery(sql)
                .unwrap(org.hibernate.Query.class) //暂不明确具体功能
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) // 将结果转成Map对象
                .getResultList();  // 返回List结果数组

        return new Result(true,resultList);	// Result类是你自己的封装对象
    }

}

你可能感兴趣的:(Java,sql,java)