views:

243

answers:

4

I'm getting started in Hibernate and so far it's not too hard. But I am confused about the hbm2ddl.auto property. Is there a way to manually execute whatever this does to initialize the database tables? I only want to do this after I make my database changes, not every time I run my program.

edit: what about at runtime? is there a way in my Java program to programmatically re-initialize the database tables? org.hibernate.tool.hbm2ddl.SchemaUpdate looks maybe like the right beast but I'm not sure what it does exactly.

+1  A: 

Use the hibernate ant tasks: https://www.hibernate.org/381.html

Gordon
+2  A: 

I would use the HBM2DDL to generate the database, then use whatever replication / backup exists on your database to save your database schema, and use that scripting to recreate your database whenever you need to; only run the HBM2DDL to generate your database when your object model changes.

McWafflestix
A: 

With this property set, you can generate create/update scripts for database and execute them. This is a great tool for prototyping, but after some time I would suggest moving to another DB update strategy.

bbmud
A: 

ok, thanks for all the clues! the following worked:

public class HibernateUtil {
...

  public static SessionFactory createSessionFactory(Properties p)
  {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
     Configuration cfg = new AnnotationConfiguration().configure();
     if (p != null)
      cfg.addProperties(p);
        return cfg.buildSessionFactory();
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
  }
}

then in my application code:

private void init() {
    Properties p = new Properties();
    p.setProperty("hibernate.hbm2ddl.auto", "create");
    Session session = HibernateUtil.createSessionFactory(p)
     .getCurrentSession();
    session.beginTransaction();
    session.getTransaction().commit();
    session.getSessionFactory().close();
    System.out.println("should be initialized....");
}
Jason S