Sunday, April 23, 2006

Getting Hibernate to Create Schema Creation SQL

I've seen some webpages that describe the SchemaExport Ant task. But it did not work when I tried to use it. The documentation for it was sparse. In any case, I traced through the underlying Hibernate code and found out that you can generate the schema creation SQL with just three lines of code:

package com.codebits;

import java.io.File;

import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.PostgreSQLDialect;

public class Play {

 public static void main(String[] args) {
  Configuration cfg = new Configuration();
  cfg.addDirectory(new File("config"));
  String[] lines = cfg.generateSchemaCreationScript(new PostgreSQLDialect());

  for (int i = 0; i < lines.length; i++) {
   System.out.println(lines[i] + ";");
  }
 }

}

Place your .hbm.xml files into some directory (I called mine config) and then execute the above class. Your schema creation script will be displayed on the console.

Wednesday, April 12, 2006

Spring, Fluent APIs, and BeanInfo

Fluent APIs use setters that return objects instead of void. Normally, Spring won't be able to use classes that implement a fluent API because the setter method won't be found. However, I have learned that it is possible to write a BeanInfo class which helps the Java reflection system. Here is a simple example:

package com.codebits;

public class PersonBeanInfo extends SimpleBeanInfo {

    public BeanDescriptor getBeanDescriptor() {
        return new BeanDescriptor(beanClass);
    }

    private final static Class beanClass = Person.class;

    public PropertyDescriptor[] getPropertyDescriptors() {
        try {

            PropertyDescriptor name = 
              new PropertyDescriptor("name", beanClass);

            PropertyDescriptor rv[] = { name };

            return rv;
        } catch (IntrospectionException e) {
            throw new Error(e.toString());
        }
    }
}

which provides guildance for this bean:

package com.codebits;

public class Person {

    private String name = null;
    
    public String getName() { return this.name; }

    public Person setName(String _name) {
        this.name = _name;
        return this;
    }

    public Person() { super(); }
}