在使用 Spring Data JPA 的時候, 通常我們只需要繼承 JpaRepository 就能獲得大部分常用的增刪改查的方法。 有時候我們需要自訂一些查詢方法, 可以寫自訂 HQL 語句
像這樣
/**
* 根據關注者id查找所有記錄(查找關注的人的id)
*
* @param fromUserId
* @return
*/
@Query("select toUserId from Relationship where fromUserId =:fromUserId")
List
但是, 有時候一些查詢比較複雜, 當我們把 SQL 語句寫好了, 卻不知道如何轉成 HQL 語句, 怎麼辦?
很簡單, Spring Data JPA 其實也支持自訂 SQL 語句查詢。
比如, 我們這裡寫了一條稍微複雜一些的 SQL 語句。
SELECT DISTINCT t1.to_user_id FROM
(SELECT * FROM relationship WHERE from_user_id = 1) AS t1
INNER JOIN relationship t2 ON t1.to_user_id = t2.from_user_id
這段 SQL 語句的作用是 查詢id=1的用戶的互相關注的用戶的id。
如何讓 JPA 幫我們查詢呢?
發現, 只需要在後面加一個 nativeQuery = true 就行, 哇, 是不是很簡單!
趕緊試試。
@Query(value = "SELECT DISTINCT t1.to_user_id FROM (SELECT * FROM relationship WHERE from_user_id = ?1) AS t1 INNER JOIN relationship t2 ON t1.to_user_id = t2.from_user_id ", nativeQuery = true)
List
寫個測試方法
package com.liuyanzhao.forum.repository;
import com.liuyanzhao.forum.entity.Relationship;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @author 言曌
* @date 2018/4/24 下午9:56
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class RelationshipRepositoryTest {
@Autowired
private RelationshipRepository relationshipRepository;
@Before
public void save() {
relationshipRepository.save(new Relationship(1L,2L));
relationshipRepository.save(new Relationship(1L,3L));
relationshipRepository.save(new Relationship(1L,4L));
relationshipRepository.save(new Relationship(2L,1L));
relationshipRepository.save(new Relationship(2L,4L));
relationshipRepository.save(new Relationship(3L,1L));
}
@Test
public void findFriendsByUserId() throws Exception {
List
System.out.println(ids);
}
}
最終查得結果 [2,3],答案正確
有坑
我們上面查到是[2,3], 這兩個數都是 bigint 類型的, 如果我們將這兩個數傳參到其他方法裡, 比如
/**
* 根據id集合查詢使用者
*
* @param ids
* @return
*/
List
會出現參數類型不匹配。
所以, 這裡我們可以把 id 的 Long 類型改成 Integer 類型, 資料表裡的 bigint 改成int
在這裡呢小編給大家推薦一個免費提升Java技術學習好地方, 課程涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高併發分散式、大資料、機器學習等技術。
轉送門:https://ke.qq.com/course/293193?flowToken=1002121