Whatever makes the most sense is the best approach.
Usually, creating it in a HibernateService or HibernateUtil class is the most flexible or manageable solution.
Here's a sweet little tutorial on how to create a HibernateUtil class in Java. It's pretty helpful:
http://jpa.ezhibernate.com/Javacode/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();
}
}