코드 그라데이션

엔티티 직접 사용 본문

Database/JPQL

엔티티 직접 사용

완벽한 장면 2023. 9. 3. 19:15

엔티티 직접 사용 - 기본 키 값

 

실습

JpqlMain

public class JpqlMain {

  public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
      Team teamA = new Team();
      teamA.setName("팀A");
      em.persist(teamA);

      Team teamB = new Team();
      teamB.setName("팀B");
      em.persist(teamB);

      Member member1 = new Member();
      member1.setUsername("회원1");
      member1.setTeam(teamA);
      em.persist(member1);

      Member member2 = new Member();
      member2.setUsername("회원2");
      member2.setTeam(teamA);
      em.persist(member2);

      Member member3 = new Member();
      member3.setUsername("회원3");
      member3.setTeam(teamB);
      em.persist(member3);


      em.flush();
      em.clear(); // 비움


      String query = "select m from Member m where m =:member";
      Member findMember = em.createQuery(query, Member.class)
          .setParameter("member", member1)
          .getSingleResult();

      System.out.println("findMember = " + findMember);
      

      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      e.printStackTrace();
    } finally {
      em.close();
    }
    emf.close();
  }
}

 

실행하면

회원1 나왔고, 물음표가 id로 변환이 되어 있음.

 

이걸 id로 바꿔도

결과는 동일하게 나올 것.

      String query = "select m from Member m where m.id =:memberId";
      Member findMember = em.createQuery(query, Member.class)
          .setParameter("memberId", member1.getId())
          .getSingleResult();

      System.out.println("findMember = " + findMember);

 

 

엔티티 직접 사용 - 외래키 값

728x90
Comments