More Books
Hibernate: A J2EE Developer's Guide
Hibernate: A J2EE™ Developer's Guide
Table of Contents
Copyright
Acknowledgments
About the Author
Preface
Required Skills
Roadmap
Chapter 1. Overview
Why Object/Relational Mapping?
What Is Hibernate?
Comparing JDBC to Hibernate
Hibernate's Mapping System
Other Java/Database Integration Solutions
How to Obtain and Install
Supported Databases
Chapter 2. Getting Oriented
Application Architecture
Mapping Files
Generating Java Source
Application Configuration
Web Application
JSP Interface
Chapter 3. Starting from Java
Java Object Model
Generated Mapping Files
Generated Schema
Working with Artifacts and Owners
Chapter 4. Starting from an Existing Schema
Initial Schema
Using Middlegen
Generated Mapping Files
Generated Java
Working with the Database
Chapter 5. Mapping Files
Basic Structure
Mapping File Reference
Chapter 6. Persistent Objects
Sessions
Objects and Identity
Life-Cycle Methods
Chapter 7. Relationships
Database Relationships
Java Collection Relationships
Java Class Relationships
Any-Based Relationships
Bi-directional Relationships
Chapter 8. Queries
HQL
HQL Reference
Select
From
Where
Group By
Having
Order By
Criteria Queries
Native SQL Queries
Chapter 9. Transactions
Introduction to Transactions
Optimistic and Pessimistic Locking
Chapter 10. Performance
Finding and Solving Problems
Queries
Inserts
Connection Pooling
Caching
Chapter 11. Schema Management
Updating an Existing Schema
Generating Update and Drop Scripts
Chapter 12. Best Practices, Style Guide, Tips and Tricks
Reducing Code with Inversion of Control
Reducing Session Creation Impact with ThreadLocal
Using Hibernate as an EJB BMP Solution
Integrating with Other Technologies
Applications That Use Hibernate
Strategies for Getting Started
Chapter 13. Future Directions
Hibernate 3.0
EJB 3.0
Here and Now
Index
SYMBOL
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X

Reducing Session Creation Impact with ThreadLocal

You can reduce the impact of retrieving a new Session object for each thread by reusing the Session for a given object. As described in Chapter 6 and Chapter 9, a Session is not sharable across threads. The code in Listing 12.3 shows a Hibernate-recommended mechanism for maintaining a per-thread Session variable. The real work of this code is done in the java.lang.ThreadLocal class, which simplifies the use of a per-thread variable.

Listing 12.3. THReadLocal Example
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory =
                  new Configuration().configure()
                         .buildSessionFactory();
        } catch (HibernateException ex) {
            throw new RuntimeException(
                  "Exception building SessionFactory: "
                        + ex.getMessage(), ex);
        }
    }

    public static final java.lang.ThreadLocal
      session = new java.lang. ThreadLocal();

    public static Session currentSession() throws
    HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void discardSession() throws
    HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
}

With luck, you should already have your Session management contained in a specific class with a static method, as shown in Chapter 2. The biggest difficulty with the pattern shown in Listing 12.3 is that a Session object can be rendered into an untenable state if a transaction-related exception is shown (Hibernate explicitly does not allow reuse of a Session object in this situation). This is why an additional discardSession() method is shown above; you need to ensure that the Session object is discarded if your application throws a transaction-related exception, as shown in the discardSession() method.