Skip to content

Instantly share code, notes, and snippets.

@brunoadacosta
Created May 8, 2012 23:11
Show Gist options
  • Save brunoadacosta/2640283 to your computer and use it in GitHub Desktop.
Save brunoadacosta/2640283 to your computer and use it in GitHub Desktop.
HibernateUtil with entity scan
package com.cocento.erp.acs.infra.database;
import java.net.URL;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import br.com.caelum.vraptor.scan.StandaloneClasspathResolver;
public class HibernateUtil {
private final Configuration cfg = new Configuration();
private final Logger logger = Logger.getLogger(HibernateUtil.class);
public HibernateUtil() {
logger.info("Hibernate Entities scan...");
URL pathToScan = new StandaloneClasspathResolver().findWebInfClassesLocation();
new EntityScanner(pathToScan).scan(cfg);
cfg.configure();
logger.info("Hibernate Entities scan done.");
}
public void createSchema() {
SchemaExport export = new SchemaExport(cfg);
export.drop(true, true);
export.create(true, true);
}
public SessionFactory createSessionFactory() {
return this.cfg.buildSessionFactory();
}
public void initDatabase(Session session) {
if (cfg.getProperty("hibernate.hbm2ddl.auto").contains("create")) {
if (!cfg.getProperty("dialect").contains("HSQLDialect")) {
new SequenceCreator(session).execute();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment