David Moreno García
David Moreno García

Reputation: 4523

Initialize Spring embedded database after deployment

I have an Spring MVC app with an embedded database (HSQLDB) that I want to initialize after deployment. I know that I could use an xml script to define initial data for my datasource but, as long I'm using JPA + Hibernate, I would like to use Java code. Is there a way to do this?

Upvotes: 0

Views: 701

Answers (1)

Pavel Horal
Pavel Horal

Reputation: 18194

Heavily updated answer (it was too complex before):

All you need is to add initializing bean to your context, which will insert all the necessary data into the database:

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

}

Upvotes: 1

Related Questions