getting hibernate to generate sql statements for my database (schema)

i needed to create the scripts needed to create a database schema for my persistence objects (JPA) using hibernate. there is a bunch of documentation about using specific ant tasks to do this. but as usual, beyond configuring ant with some arcane hibernate tools tasks etc. I found it easier to just do the following code

public class HibernateExporter {  public static void main(String[] args) {   
    System.out.println("<<<<BELOW IS THE SQL GENERATED FROM HIBERNATE IN ORDER TO CREATE THE DATABASE." + System.getProperty("line.separator") + " HOWEVER, REMEMBER TO CHECK THAT YOU MODIFIED THIS GENERATOR TO INCLUDE ALL THE RELEVANT CLASSES THE ARE TO BE PERSISTED.");
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(MyPersistentObject1.class);
    cfg.addAnnotatedClass(MyPersistentObject2.class);
    cfg.setProperty(Environment.USER, "root");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.URL, "jdbc:mysql://localhost/mfw_db");
    cfg.setProperty(Environment.DIALECT, "org.hibernate.dialect.MySQL5InnoDBDialect");
    cfg.setProperty(Environment.DRIVER, "com.mysql.jdbc.Driver");
    SchemaExport schema = new SchemaExport(cfg);    schema.setOutputFile("schema.sql");
    schema.create(true, false);  
}
}

This would, of course, require one to check that this list of classes matches the ones defined in persistence.xml, which might lead to bugs with naughty duplication and forgetting to update this one. Anyways, gets me through the day so maybe some day I will get wiser.

Generally related to this, I find it rather difficult to need to define a persistence.xml file and put it in the META-INF directory. Makes it hard to modify database parameters when you have everything packed up in a Jar file and the persistence.xml is hidden away.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s