You definitely don't want to be creating quite so many SessionFactory objects, that's for sure.
The other thing I'd say is that you probably want getSession, not openSession. There's a big difference! getSession is typically the right choice, unless you want to manage the state of the session yourself.
I've got a good tutorial on using the HibernateUtil class. You might want to create one of your own and use it:
http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=05samplehibernateutilclassexample
Code:
package com.examscam;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import com.examscam.model.User;
public class HibernateUtil {
private static SessionFactory factory;
public static Configuration
getInitializedConfiguration() {
AnnotationConfiguration config =
new AnnotationConfiguration();
/* add all of your JPA annotated classes here!!! */
config.addAnnotatedClass(User.class);
config.configure();
return config;
}
public static Session getSession() {
if (factory == null) {
Configuration config =
HibernateUtil.getInitializedConfiguration();
factory = config.buildSessionFactory();
}
Session hibernateSession =
factory.getCurrentSession();
return hibernateSession;
}
public static void closeSession() {
HibernateUtil.getSession().close();
}
public static void recreateDatabase() {
Configuration config;
config =
HibernateUtil.getInitializedConfiguration();
new SchemaExport(config).create(true, true);
}
public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
public static void commitTransaction() {
HibernateUtil.getSession()
.getTransaction().commit();
}
public static void rollbackTransaction() {
HibernateUtil.getSession()
.getTransaction().rollback();
}
public static void main(String args[]) {
HibernateUtil.recreateDatabase();
}
}
http://www.thebookonhibernate.com/HiberBookWeb/learn.jsp?tutorial=05samplehibernateutilclassexample
You might also want to look at this quick tutorial on How Hibernate Works to get a better understanding of what's going on in your code:
http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=07howhibernateworks