DAO 클래스 대체
데이터베이스 접근을 간편하게 할 수 있도록 여러 CRUD 메서드를 기본적으로 제공하는 기능을 갖고 있습니다. JpaRepository를 사용하면 별도의 구현 없이 간단히 데이터베이스 조작을 할 수 있습니다.
인터페이스 : 상속, (CrudRepository의 하위 인터페이스)
JpaRepository은 제네릭타입이기 때문에 기본자료형은 받지 못한다.
public interface MemberMemberRepository extends JpaRepository<Member, Long> {
}
find로 시작하는 메서드 : 영속 상태
get로 시작하는 메서드 : 비영속 상태 - 상태변화 감지 ❌
S save(S entity) : persist(...) : 영속성 상태로 추가
S saveAndFlush(S entity) : persist() + flush()
List<S> saveAll(Collection<S> ...)
List<S> saveAllAndFlush(....)
void delete(T entity) : remove(...)
count()
Iterable findAll()
S findOne(..)
S findById(기본키)
flush() : 상태 변화 감지 -> DB 에 반영
find 할때 내가 원하는 데이터를 찾기위해 사용
페이징 기초 정보
public interface MemberRepository extends JpaRepository<Member, Long> {
Page<Member> findByEmailContaining(String keyowrd, Pageable pageable);
}
@Test
void test3(){
Pageable pageable = PageRequest.of(1, 3);
Page<Member> data = memberRepository.findByEmailContaining("ser",pageable);
List<Member> items = data.getContent();
long total = data.getTotalElements();
System.out.printf("총 갯수 : %d\n", total);
items.forEach(System.out::println);
}

@Query 애노테이션
JPQL(Java Persistence Query Language)
| Keyword | Sample | JPQL snippet |
|---|---|---|
| And | findByLastnameAndFirstname | ... where x.lastname = ?1 and x.firstname = ?2 |
| Or | findByLastnameOrFirstname | ... where x.lastname = ?1 or x.firstname = ?2 |
| Is, Equal | findByFirstname findByFirstnameIs findByFirstnameEquals | ... where x.firstname = ?1 |
| Between | findByStartDateBetween | ... where x.startDate between ?1 and ?2 |
| LessThan | findByAgeLessThan | ... where x.age < ?1 |
| LessThanEqual | findByAgeLessThanEqual | ... where x.age <= ?1 |
| GreaterThan | findByAgeGreaterThan | ... where x.age > ?1 |
| GreaterThanEqual | findByAgeGreaterThanEqual | ... where x.age >= ?1 |
| After | findByStartDateAfter | ... where x.startDate > ?1 |
| Before | findByStartDateBefore | ... where x.startDate < ?1 |
| isNull, Null isNonNull | findByAge(is)Null | ... where x.age is null |
| NotNull | findByAge(Is)NonNull | ... where x.age not null |
| Like | findByFirstnameLike | ... where x.firstname like ?1 |
| NotLike | findByFirstnameNotLike | ... where x.fistname not like ?1 |
| StartingWith | findByFirstnameStartingWith | ... where x.firstname like ?1 (parameter bound with appended %) |
| EndingWith | findByFirstnameEndingWith | ... where x.firstname like ?1 (parameter bound prepended %) |
| Containing | findByFirstnameContaining | ... where x.firstname like ?1 (parameter bound wrapped in %) |
| OrderBy | findByAgeOrderByLastnameDesc | ... where x.age = ?1 order by x.lastname desc |
| Not | findByLastnameNot | ... where x.lastname <> ?1 |
| In | findByAgeIn(Collection\<Age> ages) | ... where x.age in ?1 |
| NotIn | findByAgeNotIn(Collection\<Age> ages) | ... where x.age not in ?1 |
| True | findByActiveTrue() | ... where x.active = true |
| False | findByActiveFalse() | ... where x.active = false |
| IgnoreCase | findByFirstnameIgnoreCase | ... where UPPER(x.firstname) = UPPER(?1) |
MemberRepository
public interface MemberRepository extends JpaRepository<Member, Long> {
//Member findMemberByEmail(String email);
//Optional<Member> findByEmail(String eamil); //null값 처리를 위해 Optional사용 가능
Member findByEmail(String eamil);
}
@SpringBootTest
@TestPropertySource(properties = "spring.profiles.active=test")
public class Ex06 {
@Autowired
private MemberRepository memberRepository;
@BeforeEach
void init() {
List<Member> members = IntStream.rangeClosed(1, 10).mapToObj(i -> Member.builder()
.email("user" + i + "@test.org")
.password("123456768")
.userName("사용자" + i)
.authority(Authority.USER)
.build()).toList();
memberRepository.saveAllAndFlush(members);
}
@Test
void test1(){
Member member = memberRepository.findByEmail("user2@test.org");
System.out.println(member);
}
}


public interface MemberRepository extends JpaRepository<Member, Long> {
//Member findMemberByEmail(String email);
//Optional<Member> findByEmail(String eamil); //null값 처리를 위해 Optional사용 가능
List<Member> findByEmailContainingAndUserNameContainingOrderByCreatedAtDesc(String eamil, String username);
}
@Test
void test2(){
List<Member> members = memberRepository.findByEmailContainingAndUserNameContainingOrderByCreatedAtDesc("ser", "용");
members.forEach(System.out::println);
}