0

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

4

1 回答 1

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;
    }

}
于 2013-07-07T20:11:27.140 回答