Named Query

XingXi·2024년 1월 8일
0

JPA

목록 보기
22/23
post-thumbnail

🍕 Reference

자바 ORM 표준 JPA 프로그래밍 : 교보문고
자바 ORM 표준 JPA 프로그래밍 - 기본편 : 인프런

Named Query

JPQL 을 미리 선언하여 사용하는 쿼리. 재사용성이 좋다.

Annotation 에 정의

@Entity
@NamedQuery(
        name = "Member.findByUserName",
        query = "select m from Member m where m.username = :username"
)
public class Member{

실행

main

            List<Member> result = em.createNamedQuery("Member.findByUserName", Member.class)
                    .setParameter("username","회원1")
                    .getResultList();
            for (Member m : result) {
                System.out.println("Member : "+m.getUsername() + "| TEAM : "+m.getTeam().getName());
            }

result

Hibernate: 
    /* Member.findByUserName */ select
        member0_.id as id1_0_,
        member0_.city as city2_0_,
        member0_.street as street3_0_,
        member0_.zipcode as zipcode4_0_,
        member0_.age as age5_0_,
        member0_.memberType as memberTy6_0_,
        member0_.TEAM_ID as TEAM_ID8_0_,
        member0_.username as username7_0_ 
    from
        Member member0_ 
    where
        member0_.username=?
Hibernate: 
    select
        team0_.id as id1_3_0_,
        team0_.name as name2_3_0_ 
    from
        Team team0_ 
    where
        team0_.id=?
Member : 회원1| TEAM : A

Loading 시점에 초기화

Application 로딩 시점에 Query 를 초기화 하여 영속성 Context의 SQL 캐시에 등록 쿼리를 검증
Member : named 쿼리 잘못 입력 시

@Entity
@NamedQuery(
        name = "Member.findByUserName",
        query = "select m from MemberADSFR m where m.username = :username"
)
public class Member{

result

org.hibernate.hql.internal.ast.QuerySyntaxException: MemberADSFR is not mapped [select m from MemberADSFR m where m.username = :username]
	at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
	at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:219)
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143)
	at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:119)
	at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
	at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
	at org.hibernate.query.spi.NamedQueryRepository.checkNamedQueries(NamedQueryRepository.java:157)
	at org.hibernate.internal.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:574)

예외가 발생하는 것을 확인할 수 있다,

0개의 댓글