users@glassfish.java.net

Glassfish and Hibernate: How to have each transction use its own session

From: <glassfish_at_javadesktop.org>
Date: Tue, 09 Jun 2009 07:28:56 PDT

I've been struggling with this for a week now and can't seem to be able to find a solution. Here is the problem:

I have a method, annotated with TransactionAttributeType.REQUIRES_NEW, that loops through a list of tasks and performs some business related work. When it is done, it calls a helper method, also annotated with TransactionAttributeType.REQUIRES_NEW, to record some performance information. I want this in its own transaction because even if I can't save the performance data, I still want to commit the business transaction.

The problem is that the 2 methods appear to be sharing the same underlying Hibernate session. When saving performance data causes a database error, the session is put in an invalid state (so states the Hibernate docs), and the business transaction gets rolled back. Looking at the logs, I see Hibernate opening a new session for the first method, but not the second.

For people who like to see code:
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public final Object execute(Object... params) {
        try {
            // do some work
        } finally {
            try {
                recordTaskMetrics(wi, tasks);
            } catch (Throwable t) {
                // eat the exception so it doesn't roll back the transaction
            }
        }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    private void recordTaskMetrics(WorkItem wi, List<ExecutableTask> tasks) {
        // save performance data to the database.
    }

Does anyone have any ideas how I can get Glassfish and Hibernate to use a new session for each new transaction?

Steve
[Message sent by forum member 'ssaliman' (ssaliman)]

http://forums.java.net/jive/thread.jspa?messageID=350042