LoginSignup
0
0

jpaリポジトリ内でSQLを作成する方法

Posted at

JPAリポジトリ内で用意されているメソッド以外を使用する方法

sample.java
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface dailyEvRepository extends JpaRepository<dailyEv, Long> {

    @Query(value = "SELECT * FROM SAMPLE WHERE id = ?1", nativeQuery = true)
    Optional<sample> findByIdCustom(Integer id);
}

注目箇所

@Query(value = "SELECT * FROM SAMPLE WHERE id = ?1", nativeQuery = true)

?1には使用する際の引数の1つ目が入ります。
nativeQuery = trueにすることでJPQLではなくSQLを使用可能になります。

例としては

Optional<Sample> sampleData = repository.findByIdCustom(1); 

だとSAMPLEテーブル内のIDが1のデータを取得します。

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0