JPA는 다양한 쿼리 방법을 지원
1. JPQL 소개
- JPQL: 엔티티 객체를 대상으로 쿼리
- 객체 지향 쿼리, 특정 데이터베이스에 의존 X- SQL: 데이터베이스 테이블을 대상으로 쿼리
List<MemberMapping> result = em.createQuery("select m from MemberMapping m where m.username like '%kim%'", MemberMapping.class).getResultList();
Hibernate:
/* select
m
from
MemberMapping m
where
m.username like '%kim%' */ select
membermapp0_.MEMBER_ID as member_i1_11_,
membermapp0_.createdAt as createda2_11_,
membermapp0_.createdBy as createdb3_11_,
membermapp0_.updatedAt as updateda4_11_,
membermapp0_.updatedBy as updatedb5_11_,
membermapp0_.city as city6_11_,
membermapp0_.street as street7_11_,
membermapp0_.zipcode as zipcode8_11_,
membermapp0_.LOCKER_ID as locker_15_11_,
membermapp0_.TEAM_ID as team_id16_11_,
membermapp0_.USERNAME as username9_11_,
membermapp0_.WORK_CITY as work_ci10_11_,
membermapp0_.WORK_STREET as work_st11_11_,
membermapp0_.WORK_ZIPCODE as work_zi12_11_,
membermapp0_.endDate as enddate13_11_,
membermapp0_.startDate as startda14_11_
from
MemberMapping membermapp0_
where
membermapp0_.USERNAME like '%kim%'
2. Criteria 소개
//Criteria 사용 준비
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MemberMapping> query = cb.createQuery(MemberMapping.class);
//루트 클래스 (조회를 시작할 클래스)
Root<MemberMapping> m = query.from(MemberMapping.class);
//쿼리 생성
CriteriaQuery<MemberMapping> cq = query.select(m);
//동적쿼리 생성에 편리
String username = "test";
if (username != null) {
cq = cq.where(cb.equal(m.get("username"),"kim"));
}
List<MemberMapping> resultList = em.createQuery(cq).getResultList();
3. QueryDSL 소개
JPAFactoryQuery query = new JPAQueryFactory(em);
QMember m = QMember.member;
List<Member> list =
query.selectFrom(m)
.where(m.age.gt(18))
.orderBy(m.name.desc())
.fetch();
4. 네이티브 SQL 소개
String sql =
“SELECT ID, AGE, TEAM_ID, NAME FROM MEMBER WHERE NAME = ‘kim’";
List<Member> resultList =
em.createNativeQuery(sql, Member.class).getResultList();
5. JDBC API를 직접 사용, MyBatis, SpringJdbcTemplate 함께 사용