部署后初始化Spring嵌入式数据库

时间:2013-07-07 18:04:59

标签: database hibernate spring-mvc jpa hsqldb

我有一个带有嵌入式数据库(HSQLDB)的Spring MVC应用程序,我希望在部署后进行初始化。我知道我可以使用xml脚本来定义我的数据源的初始数据,但是,只要我使用JPA + Hibernate,我就想使用Java代码。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

重新更新的答案(以前太复杂了):

您只需要在您的上下文中添加初始化bean,它会将所有必要的数据插入到数据库中:

public class MockDataPopulator {

    private static boolean populated = false;

    @Autowired
    private SessionFactory sessionFactory;

    @PostConstruct
    public void populateDatabase() {
        // Prevent duplicate initialization as HSQL is also initialized only once. Duplicate executions 
        // can happen when the application context is reloaded - e.g. when running unit tests).
        if (populated) {
            return;
        }
        // Create new persistence session
        Session session = sessionFactory.openSession();
        session.setFlushMode(FlushMode.ALWAYS);
        // Insert mock entities
        session.merge(MockDataFactory.createMyFirstObject())
        session.merge(MockDataFactory.createMySeconfObject())
        // ...
        // Flush and close
        session.flush();
        session.close();
        // Set initialization flag
        populated = true;
    }

}