실전! 스프링 데이터 JPA - 인프런 | 강의
스프링 데이터 JPA는 기존의 한계를 넘어 마치 마법처럼 리포지토리에 구현 클래스 없이 인터페이스만으로 개발을 완료할 수 있습니다. 그리고 반복 개발해온 기본 CRUD 기능도 모두 제공합니다.
www.inflearn.com
Spring Data JPA - Reference Documentation
Example 119. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del
docs.spring.io
사용자 정의 레퍼지토리란?
Spring Data JPA에서는 repository를 인터페이스만 정의하고 구현체는 스프링이 자동으로 생성하게된다. 다양한 이유로 repository에 메서드를 직접 구현 하고 싶을 때 repository 인터페이스의 구현체를 직접 구현하는 방법은 구현해야 하는 기능이 너무 많아 현실적으로 불가능하다. 그러므로 Spring Data JPA에서는 repository를 쉽게 확장할 수 있도록 사용자 정의 리포지토리 기능을 지원한다.
사용자 정의 리포지토리에서는 아래와같은 방법을 사용하여 메서드를 직접 구현할 수 있으나, 이번 포스팅에서는 별도로 다루지는 않는다.
- JPA의 EntityManager 객체를 직접 사용
- Spring JDBC Template
- Mybatis
- 데이터베이스 커넥션 직접사용
- QueryDsl
사용자 정의 리포지토리 구현 방법
1. 사용자 정의 리포지토리 인터페이스를 생성한다.
interface CustomMemberRepository {
void someCustomMethod(Member member);
}
2. 사용자 정의 리포지토리 인터페이스의 구현체 class를 구현한다.
class CustomiMemberRepositoryImpl implements CustomMemberRepository {
public void someCustomMethod(Member member) {
// someCustomMethod 구현
}
}
3. 확장할 리포지토리 인터페이스에 구현한 사용자 정의 리포지토리 인터페이스를 extends 시켜준다.
interface MemberRepository extends JpaRepository<Member, Long>, CustomMemberRepository {}
주의사항
CustomRepository의 구현체 class 명은 CustomRepository 명 + Impl 로 정의해야한다.
Impl대신 다른이름으로 변경하고 싶다면, 아래와 같이 repositoryImplementationPostfix 속성을 변경하면된다.
@SpringBootApplication
@EnableJpaRepositories(repositoryImplementationPostfix = "Test")
public class BbsApplication
public static void main(String[] args) {
SpringApplication.run(BbsApplication.class, args);
}
}
'Spring Data JPA' 카테고리의 다른 글
Spring Data Web 확장(도메인 클래스 컨버터 및 페이징과 정렬) (0) | 2022.12.20 |
---|---|
Auditing (0) | 2022.12.20 |
Hint & Lock (0) | 2022.12.18 |
엔티티 그래프 @EntityGraph (0) | 2022.12.18 |
벌크성 수정쿼리 @Modifying (0) | 2022.12.18 |