0

How to initialize Hibernate?

asked 2007-11-26 11:13:32 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4642258

By: enixser

After doing my first steps with ZK (creating a ZUL page) I'm now trying to use the business logic of an existing web application. That means, I want to use some classes to load objects from the database using Hibernate with annotations.

My existing application uses its own HibernateUtil class with a static block doing the configuration of Hibernate. Up to now, I use the programmatic approch for telling Hibernate which classes to use. The static block is called by a listener that is called during startup of Tomcat.

I read the small talk "Hibernate + ZK" and configured my webapp to use the HibernateSessionContextListener and the OpenSessionInViewListener. I looked into the source of HibernateUtil class and saw that in calls

new AnnotationConfiguration().configure().buildSessionFactory();

How can I do the programmatic initialization with the HibernateUtil class from zkplus.jar?

Thanks,
Ralf.

delete flag offensive retag edit

8 Replies

Sort by ยป oldest newest

answered 2007-11-27 15:48:23 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4645666

By: henrichen

HibernateUtil of zkplus.jar will read hibernate.cfg.xml at WEB-INF/classes when you first call HibernateUtil.getSesssionFactory().

/henri

link publish delete flag offensive edit

answered 2007-11-28 09:51:06 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4647231

By: enixser

Yes, I saw this when I looked into the source. But defining all mappings in hibernate.cfg.xml is not very comfortable IMO.

For my Hibernate projects I decided some time ago to use the programmatic vs.
the declarativ initialization. This way I only need to provide new mapped objects without the need to modify hibernate.cfg.xml. My initialization method than scans the packages where the mapped objects live and initializes Hibernate accordingly.

I will have a look how I can do this with the HibernateUtil class of zkplus.jar.

Regards,
Ralf.

link publish delete flag offensive edit

answered 2007-11-28 13:49:54 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4647601

By: enixser

@henri
I found a way to combine both methods (declarative AND programmatic) in one
initSessionFactory() method. Should I send the source code to you to have a look on it? If you say that my code is OK you could integrate it into HibernateUtil.

Regards,
Ralf.

link publish delete flag offensive edit

answered 2007-11-29 04:53:51 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4649083

By: henrichen

Suggestion is always welcomed :)

/henri

link publish delete flag offensive edit

answered 2007-11-29 10:43:21 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4649522

By: enixser

Here is the code. It's almost the same as the original HibernateUtil. To use the programmatic initialization you have to set a <env-entry> block in the web.xml of the web application to indicate where the mapped classes can be found.

<env-entry>
<env-entry-name>hibernate.daoPackage</env-entry-name>
<env-entry-value>xxx.yyy.zzz</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

Maybe there is a better way configure this, but at the moment it works for my application and I did find a better solution.

public class MyHibernateUtil
{
private static Logger logger = Logger.getLogger (HibernateUtil.class);

private static SessionFactory sessionFactory;

/* package */ static void initSessionFactory()
{
logger.debug("Initializing Hibernate session factory...");
try
{
//-----------------------------------------------------------------------
// Create the SessionFactory from hibernate.cfg.xml and register all
// classes of the package defined by the system property
// "hibernate.daoPackage" as DAO classes.
//-----------------------------------------------------------------------
AnnotationConfiguration config = new AnnotationConfiguration();

for (Class clazz : getClasses ())
config.addAnnotatedClass (clazz);

sessionFactory = config.configure().buildSessionFactory();
}
catch (Throwable ex)
{
//-----------------------------------------------------------------------
// Make sure you log the exception, as it might be swallowed
//-----------------------------------------------------------------------
logger.fatal ("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

/* package */ static void cleanupSessionFactory()
{
logger.debug("Freeing all Hibernate resources...");
if (sessionFactory != null)
{
sessionFactory.close(); // Free all resources
sessionFactory = null;
}
}

public static SessionFactory getSessionFactory()
{
if (sessionFactory == null)
initSessionFactory();

return sessionFactory;
}


public static Session getCurrentSession() throws HibernateException
{
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
return session;
}

public static void closeCurrentSession() throws HibernateException
{
getSessionFactory().getCurrentSession().close();
}

private static List<Class> getClasses() throws ClassNotFoundException
{
ArrayList<Class> classes = new ArrayList<Class>();

//-------------------------------------------------------------------------
// Get a File object for the package
//-------------------------------------------------------------------------
String daoPackage = null;

try
{
Context env = (Context) new InitialContext().lookup("java:comp/env");
daoPackage = (String)env.lookup("hibernate.daoPackage");
}
catch (Exception e)
{
e.printStackTrace();
}

File directory = null;
try
{
if (daoPackage == null)
return classes;

directory = new
File(Thread.currentThread().getContextClassLoader().getResource('/'
+ daoPackage.replace('.', '/')).getFile());
}
catch(NullPointerException x)
{
throw new ClassNotFoundException (daoPackage + " does not appear to be a valid package");
}

if (directory.exists())
{
//------------------------------------------------------------------------
-
// Get the list of the files contained in the package
//------------------------------------------------------------------------
-
String[] files = directory.list();
for(int i = 0; i < files.length; i++)
{
//----------------------------------------------------------------------
---
// We are only interested in .class files
//----------------------------------------------------------------------
---
if (files[i].endsWith(".class"))
{
classes.add (Class.forName(daoPackage + "." + files[i].substring(0, files[i].length()-6)));
}
}
}
else
{
throw new ClassNotFoundException(daoPackage + " does not appear to be a valid package");
}
return classes;
}
}


link publish delete flag offensive edit

answered 2007-11-30 00:47:42 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4650960

By: henrichen

Can you provide example contents of the daoPackage file?

/henri

link publish delete flag offensive edit

answered 2007-11-30 07:21:52 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4651346

By: enixser

daoPackage points to a package, not a file. It's the root directory from where the getClasses() method will search recursively for class files. All the class files in this package and its subpackages will be used as mapped files.

Regards,
Ralf.

link publish delete flag offensive edit

answered 2007-12-02 02:40:52 +0800

admin gravatar image admin
18691 1 10 130
ZK Team


Orignial message at:
https://sourceforge.net/forum/message.php?msg_id=4653996

By: henrichen

This is an interesting approach. However, I think it is somehow beyond the scope of the ZK project. I will suggest that you propose this to Hibernate Project directly that they might add this spec. into their configuration files or classes.

What we will do is to "ease" the operation to "glue" ZK and Hibernate or something alike.

/henri

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2007-11-26 11:13:32 +0800

Seen: 246 times

Last updated: Dec 02 '07

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More