Sự khác nhau giữa openSession() và getCurrentSession() trong Hibernate

Sự khác nhau giữa openSession() và getCurrentSession() trong Hibernate.

Hibernate openSession và getCurrentSession

Trong Hibernate, khi bạn lấy một session từ đối tượng SessionFactory, bạn có thể sử dụng openSession hoặc getCurrentSession. Nếu bạn sử dụng openSession, nó sẽ mở một session mới. Nếu bạn sử dụng getCurrentSession, nó sẽ lấy session hiện tại từ thread context đang tồn tại.

1. getCurrentSession

Để sử dụng getCurrentSession, bạn cần phải cấu hình hibernate.current_session_context_class trong file cấu hình hibernate. Ví dụ:

  <session-factory>
      ...
      <property name="hibernate.current_session_context_class">
      	org.hibernate.context.internal.ThreadLocalSessionContext
      </property>
  </session-factory>

Nếu không có cấu hình trên thì bạn sẽ gặp lỗi:

org.hibernate.HibernateException: No CurrentSessionContext configured!

getCurrentSession() thì session sẽ tự động đẩy dữ liệu (flush()) và đóng (close()) session.

Khi lấy session từ getCurrentSession() mà thực hiện 2 thao tác truy vấn bạn sẽ gặp lỗi Session is closedvì sau lần truy vấn thứ nhất, session đã bị close.

2. openSession

Đối với phương thức openSession(), sau khi truy vấn dữ liệu (thêm, xóa, sửa) thì session vẫn còn giữ và không tự động đẩy (flush()) hay close mà bạn phải tự làm việc này.

Dưới đây là code ví dụ với session, các bạn có thể sửa thành getCurrentSession để thực hiện truy vấn.

Code ví dụ Hibernate SessionFactory, Session

Sự khác nhau giữa openSession() và getCurrentSession() trong Hibernate stackjava.com

Okay, Done!

 

References:

https://docs.jboss.org/hibernate/…/SessionFactory.html

stackjava.com