package org.jboss.test.hibernate;
import org.jboss.test.hibernate.model.User;
import org.jboss.naming.Util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class ProfileService
{
private static final String SESSION_FACTORY_NAME = "java:/hibernate/SessionFactory";
public User loadUser(long id) throws HibernateException
{
return loadUser( new Long(id) );
}
public User loadUser(Long id) throws HibernateException
{
return (User) getSession().load(User.class, id);
}
public List listUsers() throws HibernateException
{
return getSession()
.createQuery("from User")
.list();
}
public User locateUser(String handle) throws HibernateException
{
return (User) getSession()
.createQuery("from User as u where u.handle = :handle")
.setString("handle", handle)
.uniqueResult();
}
public User storeUser(User user) throws HibernateException
{
getSession().saveOrUpdate(user);
getSession().flush();
return user;
}
private Session getSession()
{
try
{
SessionFactory sf = ( SessionFactory ) Util.lookup( SESSION_FACTORY_NAME, SessionFactory.class );
return sf.getCurrentSession();
}
catch( HibernateException e )
{
throw e;
}
catch( Exception e )
{
throw new HibernateException( "Unable to locate current session", e );
}
}
}