💫 사용 예시
interface UserRepositoryextends Repository<User, Long> {
List<User> findByAddressAndLastname(Address address, String lastname);
// “select u from User u where u.address= ?1 and u.lastname= ?2”
List<User> findDistinctUserByLastnameOrFirstname(String lastname, String firstname);
// 또는 List<User> findUserDistinctByLastnameOrFirstname(String lastname, String firstname);
// “select distinct u from User u where u.lastname= ?1 or u.firstname= ?2”
List<User> findByLastnameOrderByFirstnameAsc(String lastname);
// “select u from User u where u.lastname= ?1 order by u.firstnameasc”
List<User> findByAddressOrderByFirstnameDescLastnameAsc(Address address);
// “select u from User u where u.address= ?1 order by u.firstnamedesc, u.lastnameasc”
longcountByLastname(String lastname); // count 질의
// “select count(u) from User u where u.lastname= ?1”
}
1) Entity에 대한 Repository interface(DAO) 정의
interface ProductRepositoryextends CrudRepository<Product, String> {
// CrudRepository에포함된save(), findById(), count(), delete() 등은자동상속됨
// query method 추가선언
List<Product> findByName(String name);
List<Product> findByCategoryId(String categoryId);
long countByCategoryId(String categoryId);
long deleteByCategoryId(String categoryId);
…
}
2) Service class에서 Repository 객체에 대한 DI 설정
3) Service class에서 Repository에 정의된 method 이용(호출)
// 2,3) 같이 구현
@Service
public class PetStoreService{
@Autowired
private ProductRepositoryprodRepository; // ProductRepository객체 주입
public void setProdRepository(ProductRepositoryprodRepository) {
this.prodRepository= prodRepository;
}
public Product getProduct(String productId) { // ProductRepository이용
Optional<Product> result = prodRepository.findById(productId);
if (result.isPresent()) return result.get(); // 상속된 메소드 호출
return null;
}
@Transactional
public long deleteProductByCategory(String categoryId) {
return prodRepository.deleteByCategoryId(categoryId);
} // 추가정의된 메소드 호출
…
}