Tuesday, September 3, 2013

Hibernate configuration example with in-memory H2 DB for ad-hoc testing

    Sometimes I like to play a little bit with Hibernate. I do not want to spend much time on configuration or DB schema creation so I keep prepared piece of code.
Here it is:
public class HibernateConfig {

 public static void main(String[] args) throws Exception {
  SessionFactory sessionFactory = new Configuration()
  .addAnnotatedClass(Entity.class)
  .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
  .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
  .setProperty("hibernate.current_session_context_class", "thread")
  .setProperty("hibernate.show_sql", "true")
  .setProperty("hibernate.hbm2ddl.auto", "create")
  .buildSessionFactory();
  
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  // PLAY HERE 
  session.getTransaction().commit();
 }
}
and my dependencies from pom.xml:
<dependencies>
 <dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>3.6.10.Final</version>
 </dependency>
 <dependency>
  <groupId>javassist</groupId>
  <artifactId>javassist</artifactId>
  <version>3.12.1.GA</version>
 </dependency>
 <dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <version>1.3.173</version>
 </dependency>
</dependencies> 

No comments :

Post a Comment