Tham khảo tài liệu 'manning hibernate in action phần 9', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 302 CHAPTER 8 Writing Hibernate applications try if s null s s catch HibernateException ex throw new InfrastructureException ex return s public static void closeSession try Session s Session null if s null catch HibernateException ex throw new InfrastructureException ex public static void beginTransaction F Transaction tx Transaction try if tx null tx getSession .beginTransaction tx catch HibernateException ex throw new InfrastructureException ex public static void commitTransaction F Transaction tx Transaction try if tx null null catch HibernateException ex rollbackTransaction throw new InfrastructureException ex public static void rollbackTransaction Transaction tx Transaction try null if tx null Designing layered applications 303 catch HibernateException ex throw new InfrastructureException ex finally closeSession o The Session of the current thread is stored in this ThreadLocal variable. We use one database transaction for all operations so we use another ThreadLocal for the Transaction. Both Session and Transaction are now associated with the thread and many action executions in a thread can participate in the same database transaction. The getSession method has been extended to use the thread-local variable we also wrap the checked HibernateException in an unchecked InfrastructureException part of CaveatEmptor . We also wrap the exceptions thrown by in this static helper method. The code used to start a new database transaction is similar to the getSession method. If committing the database transaction fails we immediately roll back the transaction. We don t do anything if the transaction was already committed or rolled back. After .