Spring Boot Data Jpa 어플리케이션에서 기준 쿼리를 사용하는 방법
Spring Boot Data jpa를 사용하는 어플리케이션이 있습니다. 지금까지 저는 이런 저장소를 사용하고 있습니다.
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>{
@Query(value = ""
+ "SELECT s.studentname "
+ "FROM studententity s, "
+ " courseentity c "
+ "WHERE s.courseid = c.courseid "
+ " AND s.courseid IN (SELECT c.courseid "
+ " FROM courseentity c "
+ " WHERE c.coursename = ?1)")
List<String> nameByCourse(String coursename);
}
스프링 부트 응용 프로그램에서 최대 절전 모드가 이러한 경우에 제공하는 기준 쿼리를 어떻게 사용할 수 있습니까?
에서
사용자 지정 기능으로 리포지토리를 강화하려면 먼저 사용자 지정 기능에 대한 인터페이스 및 구현을 정의합니다.제공한 리포지토리 인터페이스를 사용하여 사용자 지정 인터페이스를 확장합니다.
인터페이스를 다음과 같이 정의합니다.
public interface StudentRepositoryCustom {
List<String> nameByCourse(String coursename);
}
그런 다음 이 인터페이스의 사용자 정의 구현을 정의합니다.
@Service
class StudentRepositoryImpl implements StudentRepositoryCustom {
@PersistenceContext
private EntityManager em;
public List<String> nameByCourse(String coursename) {
CriteriaBuilder cb = em.getCriteriaBuilder();
//Using criteria builder you can build your criteria queries.
}
}
이제 JPA 저장소에서 이와 같은 사용자 지정 저장소 구현을 확장할 수 있습니다.
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>, StudentRepositoryCustom {
}
기준 쿼리 및 기준 작성기에 대해 자세히 알아보기
와 함께Spring-boot-jpa
사용할 수 있습니다.entityManager
거의 모든 곳에가장 일반적인 방법은 자신의 것을 만드는 것입니다.interface
사용자 지정 방법의 경우.
public interface StudentCustomRepository {
void anyCustomMethod();
Student getStudentByName(String name);
}
그런 다음 이 인터페이스를 자동 배선 및 사용할 수 있는 서비스 클래스에 구현합니다.entityManager
:
@Service
public class StudentCustomRepositoryServiceImpl implements StudentCustomRepository {
@PersistenceContext
private EntityManager em;
@Override
public void anyCustomMethod(){
//here use the entityManager
}
@Override
StudentEntity getStudentByName(String name){
Criteria crit = em.unwrap(Session.class).createCriteria(StudentEntity.class);
crit.add(Restrictions.eq("name", name));
List<StudentEntity> students = crit.list();
return students.get(0);
}
}
또한 다음을 구현하도록 결정할 수 있습니다.StudentRepository
새로운StudentCustomRepositoryServiceImpl
학급.
JPA 2는 프로그래밍 방식으로 쿼리를 작성하는 데 사용할 수 있는 기준 API를 도입합니다.
에서 새 인터페이스를 확장할 수 있습니다.JpaSpecificationExecutor
public interface CustomerRepository extends
CrudRepository<Customer, Long>,
JpaSpecificationExecutor<Customer> {
default List<Customer> findCustomers() {
return findAll(CustomerSpecs.findCustomers());
}
그런 다음 고객 사양을 작성합니다.
public final class CustomerSpecs {
public static Specification<Customer> findCustomers() {
return new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
CriteriaBuilder builder) {
LocalDate date = new LocalDate().minusYears(2);
return builder.lessThan(root.get("birthday"), date);
}
};
}
위의 내용은 다음과 같이 람다를 사용하여 단순화할 수 있습니다.
public interface CustomerRepository extends
CrudRepository<Customer, Long>,
JpaSpecificationExecutor<Customer> {
default List<Customer> findCustomers() {
return findAll(
(root, query, cb) -> {
LocalDate date = new LocalDate().minusYears(2);
return cb.lessThan(root.get("birthday"), date);
}
);
}
자세한 내용은 이 스프링 문서를 참조하십시오.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/ # 사양
Springdoc HibernateTemplate에 따르면:
참고: 최대 절전 모드 액세스 코드는 일반 최대 절전 모드 스타일로 코딩할 수도 있습니다.따라서 새로 시작한 프로젝트의 경우 SessionFactory.getCurrentSession()을 기반으로 데이터 액세스 개체를 코딩하는 표준 Hibernate 스타일을 대신 채택하는 것이 좋습니다.이 HibernateTemplate는 주로 Hibernate 3 기반 데이터 액세스 코드에 대한 마이그레이션 도우미로 존재하며 Hibernate 4.x의 버그 수정을 활용합니다.
Hibernate 문서에 따르면:
새로운 개발은 JPA javax.persistence.criteria에 초점을 맞춰야 합니다.기준 쿼리 API.최종적으로 최대 절전 모드별 기준 기능은 JPA javax.persistence.criteria의 확장으로 포팅됩니다.기준 쿼리.
따라서 JPQL 기준을 사용하는 것이 좋습니다.JPA 기준 API 쿼리
예:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Country> q = cb.createQuery(Country.class);
Root<Country> c = q.from(Country.class);
q.select(c);
여기서 entityManager는 @Autowired여야 합니다.자세한 내용은 위 링크를 참조하십시오.
쿼리 생성을 봄 데이터 JPA 문서로 참조하여 표를 볼 수 있습니다. JPA는 문자열 쿼리를 사용하지 않을 수 있는 메서드 이름에서 여러 쿼리 생성을 제공합니다.
언급URL : https://stackoverflow.com/questions/44278066/how-to-use-criteria-queries-in-spring-boot-data-jpa-application
'source' 카테고리의 다른 글
Flexible Array 멤버가 구조 오류 끝에 있지 않은 원인은 무엇입니까? (0) | 2023.07.23 |
---|---|
두 장고 쿼리 세트의 결합을 어떻게 찾을 수 있습니까? (0) | 2023.07.23 |
react-native: 명령을 찾을 수 없습니다. (0) | 2023.07.23 |
Python 및 Scrapy 및 MariaDB/MYSQL 데이터베이스로 스크랩된 데이터 가져오기 시도 (0) | 2023.07.23 |
MySQL/MariaDB에서 문자열(uuid)을 정수와 동일하게 간주하는 이유는 무엇입니까? (0) | 2023.07.23 |