Spring Data JPAはSQL文を書いてもいいです。

2971 ワード

Spring Dataを使っています。 JPA 私たちは通常相続だけが必要です。 Jparepositoryは大部分の常用する添削添削の調査の方法を獲得することができます。ユーザー定義の問い合わせ方法が必要な場合があります。ユーザー定義のHQL文を書くことができます。
このように
    /**
     *      id      (       id)
     *
     * @param fromUserId
     * @return
     */
    @Query("select toUserId from Relationship where fromUserId =:fromUserId")
    List findByFromUserId(@Param("fromUserId") Long fromUserId);
 
しかし、いくつかの検索は複雑です。SQL文を書いたら、どうやってHQL文に変えたらいいか分かりません。どうすればいいですか?
簡単です。Spring Data JPA カスタムSQL文クエリもサポートされています。
例えば、ここでは少し複雑なSQL文を書きました。
SELECT DISTINCT t1.from_user_id FROM
(SELECT * FROM relationship WHERE to_user_id = 1)  AS t1
INNER JOIN relationship t2 ON t1.from_user_id = t2.to_user_id
このSQL文の役割は、id=1のユーザの相互関心のあるユーザのIDを照会することである。
 
どうやって譲りますか JPA 調べてもらえますか?
私達は文書を調べます。これをクリックして直接行けばいいです。
あとに一つだけ追加してください。 native Query=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 findFriendsByUserId(Long userId);
 
テスト方法を書きます
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 ids = relationshipRepository.findFriendsByUserId(1L);
        System.out.println(ids);
    }

}
 
最終的に調べた結果[2,3]が正解です。
 
 
穴がある
上で調べたのは[2,3]です。この二つの数は全部ビギナートタイプです。もしこの二つの数を他の方法に伝えたら、例えば。
/**
  *   id      
  *
  * @param ids
  * @return
  */
 List findByIdIn(List ids);
パラメータタイプが一致しない場合があります。
したがって、ここではIDのLongタイプをIntegerタイプに変更できます。データテーブルのbigintをintに変更します。
 
文書の直通:https://docs.spring.io/spring-data/jpa/docs/1.10.2.RELEASE/reference/html/#jpa.query-methods.at-query
原文の住所:https://liuyanzhao.com/8069.html