티스토리 뷰

728x90

1. 저장하기

  1-1 save 메소드는 생성된 id를 반환한다.

 

2. 하나의 객체 가져오기

  2-1. 객체를 지정된 클래스로 반환하고, 없으면 null이 반환된다.

 

// 저장하기
    SessionFactory factory = new Configuration()
        .configure("hibernate.cfg.xml")
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();

    Session session = factory.getCurrentSession();

    try {
      Student tempStudent = new Student("Pilseong", "Heo", "heops79@gmail.com");
      
      session.beginTransaction();
      
      session.save(tempStudent);
      
      session.getTransaction().commit();
      
    } finally {
      factory.close();
    }
    
// 하나의 객체 가져오기, 없으면 null이 반환된다.
    SessionFactory factory = new Configuration()
        .configure()  // parameter가 없으면 hibernate.cfg.xml이 기본값이다.
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    
    try {
      session.beginTransaction();
      
      System.out.println(session.get(Student.class, 1L).toString());
      System.out.println(session.get(Student.class, 2L).toString());
      System.out.println(session.get(Student.class, 3L).toString());
      
      
      session.getTransaction().commit();
    } finally{
      factory.close();
    }
  }

 

3. HQL Query 사용하기

  3-1 아래 코드의 queryString에서 원하는 Query구문을 사용할 수 있다.

  3-2 여기에서 사용되는 query 상 table과 column은 Entity Class와 instance로 대체되어야 한다.

 

public class RetrieveAllStudent {

  public static void main(String[] args) {
    
    SessionFactory factory = new Configuration()
        .configure()
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    
    String queryString = "from Student s where s.lastName='Heo' or s.firstName='Paul'";
    List<Student> students = session.createQuery(queryString, Student.class).getResultList();
    
    displayStudents(students);

    session.getTransaction().commit();
    factory.close();
  }

  private static void displayStudents(List<Student> students) {
    System.out.println("Retrieved Student");
    students.stream().forEach(System.out::println);
   
    System.out.println("End Of Students \n");
  }
}

 

  3-3 결과값은 아래와 같다.

 

Retrieved Student
Student(id=1, firstName=Paul, lastName=Wall, email=paul@gmail.com)
Student(id=2, firstName=Pilseong, lastName=Heo, email=heops79@gmail.com)
End Of Students 

 

4. Update 하기

  4-1 upate시에는 별도로 save를 호출할 필요가 없다.

    4-1-1 transaction을 시작해서 entity를 불러오면 hibernate가 내부적으로 관리하므로 commit만 하면 된다.

  

  4-2 절차 

    4-2-1 Transaction을 시작한다.

    4-2-2 우선 수정할 객체를 불러혼다.

    4-2-3 setter 통해 수정한다.

    4-2-4 commit한다.

 

public class UpdateStudent {
  public static void main(String[] args) {
    SessionFactory factory = new Configuration()
        .configure()
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    
    Student student = session.get(Student.class, 1L);
    System.out.println("Target Stduent:: " + student.toString());
    
    student.setEmail("foo@gmail.com");
    
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    student = session.get(Student.class, 1L);
    System.out.println("Updated Stduent:: " + student.toString());
    
    session.getTransaction().commit();
    factory.close();
  }
}

 

    4-2-5 결과값은 아래와 같다.

 

Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
Target Stduent:: Student(id=1, firstName=Paul, lastName=Wall, email=paul@gmail.com)
Hibernate: update student set email=?, first_name=?, last_name=? where id=?
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
Updated Stduent:: Student(id=1, firstName=Paul, lastName=Wall, email=foo@gmail.com)

 

  4-3. 하나가 아닌 많은 양의 데이터를 udpate할 경우는 createQuery를 사용한다.

    4-3-1 아래는 모든 student의 email을 foo@gmail.com 변경하는 예제이다.

 

String queryString = "update Student set email='foo@gmail.com";
session.createQuery(queryString).executeUpdate();

 

  4-4 위의 것들을 응용한 소스

 

public class UpdateStudent {
  public static void main(String[] args) {
    SessionFactory factory = new Configuration()
        .configure()
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    
    Student student = session.get(Student.class, 1L);
    System.out.println("Target Stduent:: " + student.toString());
    
    student.setEmail("foo@gmail.com");
    
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    student = session.get(Student.class, 1L);
    System.out.println("Updated Stduent:: " + student.toString());
    
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    String queryString = "update Student set firstName='yoohoo'";
    session.createQuery(queryString).executeUpdate();
    
    List<Student> students = session.createQuery("from Student", Student.class).getResultList();
    displayStudents(students);
    
    session.getTransaction().commit();
    factory.close();
  }

  private static void displayStudents(List<Student> students) {
    System.out.println("\n Updated Students ");
    students.stream().forEach(System.out::println);
    System.out.println("\n End of updated Students \n");
  }
}

 

    4-4-1 출력된 로그파일

 

Target Stduent:: Student(id=1, firstName=Paul, lastName=Wall, email=paul@gmail.com)
Updated Stduent:: Student(id=1, firstName=Paul, lastName=Wall, email=foo@gmail.com)

Updated Students 
Student(id=1, firstName=yoohoo, lastName=Wall, email=foo@gmail.com)
Student(id=2, firstName=yoohoo, lastName=Heo, email=heops79@gmail.com)

 End of updated Students 

 

5. Delete 하기

  5-1 삭제할 entity를 가지고 온 후 delete하면 된다.

 

public class DeleteStudents {
  public static void main(String[] args) {
    SessionFactory factory = new Configuration()
        .configure()
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    
    Student student = session.get(Student.class, 1L);
    System.out.println("Target Student:: " + student.toString());
    
    session.delete(student);
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    student = session.get(Student.class, 1L);
    if (student == null) {
      System.out.println("\n Student is not found \n");
    }
    
    session.getTransaction().commit();
    factory.close();
  }
}

 

  5-2 결과는 다음과 같다.

 

Target Student:: Student(id=1, firstName=Pilseong, lastName=Heo, email=heops79@gmail.com)

 Student is not found 


 

  5-3 삭제를 하는 다른 방법도 있다.

    5-3-1 update와 동일하게 createQuery를 사용하는 것이다.

 

public class DeleteStudents {
  public static void main(String[] args) {
    SessionFactory factory = new Configuration()
        .configure()
        .addAnnotatedClass(Student.class)
        .buildSessionFactory();
    
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    
    Student student = session.get(Student.class, 4L);
    System.out.println("Target Student:: " + student.toString());
    
    session.delete(student);
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    student = session.get(Student.class, 4L);
    if (student == null) {
      System.out.println("\n Student is not found \n");
    }
    
    session.getTransaction().commit();
    
    session = factory.getCurrentSession();
    session.beginTransaction();
    
    String queryString = "Delete from Student s where s.firstName='pilseong'";
    session.createQuery(queryString).executeUpdate();
    
    session.getTransaction().commit(); 
    factory.close();
  }
}
728x90
댓글