Spring Data JPA 實現聯表查詢

空門.發表於2020-03-22

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<HashMap<String,Object>> resultList = entityManager.createNativeQuery(sql)
                .unwrap(org.hibernate.Query.class) //暫不明確具體功能
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) // 將結果轉成Map物件
                .getResultList();  // 返回List結果陣列

        return new Result(true,resultList);	// Result類是你自己的封裝物件
    }

}

相關文章