Initializing Hibernate without XML
April 13th, 2010 | By Christoph in Software-Development | No Comments »This article just shows a code snippet I have used for initializing Hibernate in pure JAVA code without the hibernate.xml which you would normally use.
public void start(BundleContext context) throws Exception { initHibernate(context); } private void initHibernate(BundleContext context) { try { final AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); cfg.setProperty("hibernate.connection.url", applicationRegistry.getAppProperties().getDbConnectionUrl()); // e.g. "jdbc:mysql://localhost:3306/mydatabase" cfg.setProperty("hibernate.connection.username", applicationRegistry.getAppProperties().getDbUser()); cfg.setProperty("hibernate.connection.password", applicationRegistry.getAppProperties().getDbPassword()); cfg.setProperty("hibernate.connection.pool_size", "5"); cfg.setProperty("hibernate.connection.autocommit", "false"); cfg.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider"); //cfg.setProperty("hibernate.hbm2ddl.auto", "create-drop"); cfg.setProperty("hibernate.show_sql", "true"); cfg.setProperty("hibernate.format_sql","true"); cfg.setProperty("hibernate.use_sql_comments","true"); cfg.setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory"); cfg.setProperty("hibernate.current_session_context_class", "thread"); cfg.setProperty("org.hibernate.flushMode", "COMMIT"); cfg.setProperty("hibernate.generate_statistics", "true"); // Hibernate entities cfg.addAnnotatedClass(com.myproject.model.entities.Project.class); cfg.addAnnotatedClass(com.myproject.model.entities.Customer.class); // ... and so on... sessionFactory = cfg.buildSessionFactory(); org.springframework.orm.hibernate3.HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory); applicationRegistry.setTransactionHelper(new TransactionHelper(transactionManager)); } catch (Exception e) { LOGGER.error("Error", e.getMessage(), e); } }
That’s it. I am using this code with Hibernate 3 using Annotations and so far it does what I want and it is not more ugly than the hibernate.xml (although that is in the eye of the observer
)