2013年1月8日 星期二

Hibernate hbm2ddl API

Hibernate提供了hbm2ddl的設定可以在啟動時create table schema,那麼這個API在哪呢?
答案是:org.hibernate.tool.hbm2ddl.SchemaExport
以下是將script打印在console上,而不真的執行sql的程式範例。
代碼:
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles("test")
public class ExportCreateScript {
    @Autowired
    private AnnotationSessionFactoryBean sessionFactory;

    @Test
    public void test() {
        SchemaExport export = new SchemaExport(sessionFactory.getConfiguration());
        export.setDelimiter(";");
        export.create(true, false);
    }
}