-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: Session demarcation in nested functions
PostPosted: Fri Feb 17, 2006 7:34 am 
Newbie

Joined: Wed Jan 18, 2006 2:19 pm
Posts: 14
Hi. I've got method
Code:
public User getUser(Integer id){
        Session session=null;
        try{
            session=HibUtil.getSessionFactory().openSession();
            return (User) session.get(User.class, id);
        }catch (HibernateException ex){
        ...
        return user;
}


and I'm calling this method in
Code:
public Loan newLoan(Integer userId, Integer exemplarId){
        Session session=null;
        Transaction tx=null;
        Loan loan;
        try{
            session=HibUtil.getSessionFactory().openSession();
            tx=session.beginTransaction();
            loan=new Loan();
/*--->*/loan.setUser(getUser(userId));
            loan.setExemplar(getExemplar(exemplarId));
            session.save(loan);
           tx.commit();
        }catch (HibernateException ex){
        ...
        return loan;
}


I'd like to ask wheter new session is obtained for the nested getUser method. And if it's true, if there is any standard way how to write getUser method when I want to call it both nested and separately and i don't want to create needless session in nested call?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 17, 2006 8:22 am 
Beginner
Beginner

Joined: Fri May 13, 2005 9:39 am
Posts: 21
Hi,
you can create a session factory that get the current session if it exists.
To do so, instantiate in your session factory, the session as thread locale.

My IDE builds for me a quite efficient session factory.

Code:
package mypackages;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * NOTICE: Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file. That
     * is place the config file in a Java package - the default location
     * is the default Java package.<br><br>
     * Examples: <br>
     * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
     * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
     */
    private static String CONFIG_FILE_LOCATION = "mypackages/hibernate.cfg.xml";

    /** Holds a single instance of Session */
    private static final ThreadLocal threadLocal = new ThreadLocal();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
       
        if (session == null) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     * Default constructor.
     */
    private HibernateSessionFactory() {
    }

}

With this factory, you never call the openSession method, but you call in a static way:
Code:
org.hibernate.Session session = mypackages.HibernateSessionFactory.currentSession();


I hope it's useful

Marcel[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 17, 2006 2:45 pm 
Expert
Expert

Joined: Tue Nov 23, 2004 7:00 pm
Posts: 570
Location: mostly Frankfurt Germany
I quite offen test, if a transaction is open in a business method. If not my business method is reponsible for the transaction and saves a boolean flag and commits the transaction at the end.

Sebastian

_________________
Best Regards
Sebastian
---
Training for Hibernate and Java Persistence
Tutorials for Hibernate, Spring, EJB, JSF...
eBook: Hibernate 3 - DeveloperGuide
Paper book: Hibernate 3 - Das Praxisbuch
http://www.laliluna.de


Top
 Profile  
 
 Post subject:
PostPosted: Mon Apr 03, 2006 1:05 pm 
Newbie

Joined: Wed Jan 18, 2006 2:19 pm
Posts: 14
LaLiLuna wrote:
I quite offen test, if a transaction is open in a business method. If not my business method is reponsible for the transaction and saves a boolean flag and commits the transaction at the end.


That's exactly what I want.. Is there any way to write this conditional session closing in something like hibernateUtil class?


Top
 Profile  
 
 Post subject:
PostPosted: Tue Apr 04, 2006 6:42 pm 
Expert
Expert

Joined: Tue Nov 23, 2004 7:00 pm
Posts: 570
Location: mostly Frankfurt Germany
Hibernate Util class is just a simple class. You could adapt the source code to your needs. Just add a method.

Best Regards

Sebastian

_________________
Best Regards
Sebastian
---
Training for Hibernate and Java Persistence
Tutorials for Hibernate, Spring, EJB, JSF...
eBook: Hibernate 3 - DeveloperGuide
Paper book: Hibernate 3 - Das Praxisbuch
http://www.laliluna.de


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.