[스프링 데이터 JPA] JPA 프로그래밍 7: Query
JPQL (HQL)
- Java Persistence Query Language / Hibernate Query Language
- 데이터베이스 테이블이 아닌, 엔티티 객체 모델 기반으로 쿼리 작성
- JPA 또는 하이버네이트가 해당 쿼리를 SQL로 변환해서 실행함
- https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#hql
Hibernate ORM 5.2.18.Final User Guide
Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat
docs.jboss.org
Criteria
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#criteria
Hibernate ORM 5.2.18.Final User Guide
Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat
docs.jboss.org
Native Query
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#sql
Hibernate ORM 5.2.18.Final User Guide
Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat
docs.jboss.org
QueryRunner를 통한 테스트
@Component
@Transactional
public class QueryRunner implements ApplicationRunner {
@PersistenceContext
EntityManager entityManager;
@Override
public void run(ApplicationArguments args) throws Exception {
/**
* JPQL - 타입세이프 X
*/
TypedQuery<Post> query = entityManager.createQuery("SELECT p FROM Post AS p", Post.class); // Post는 엔티티 이름이다.
List<Post> jpqlResultList = query.getResultList();
jpqlResultList.forEach(p -> System.out.println(p.toString()));
/**
* Criteria - 타입세이프 O
* */
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Post> criteriaQuery = builder.createQuery(Post.class);
Root<Post> from = criteriaQuery.from(Post.class);
criteriaQuery.select(from);
List<Post> criteriaResultList = entityManager.createQuery(criteriaQuery).getResultList();
criteriaResultList.forEach(p -> System.out.println(p.toString()));
/**
* Native Query
* */
List<Post> nativeQueryResultList = entityManager.createNativeQuery("SELECT * FROM POST", Post.class).getResultList();
nativeQueryResultList.forEach(p -> System.out.println(p.toString()));
}
}