golinko
golinko

Reputation: 347

hibernate populate table if empty

I have an entity class and I want hibernate to populate the corresponding table in DB with some constant values: several rows with some data (if there is no values in it, or replace...) How can I ask hibernate to do this (ideally with annotations)?

I'm using hibernate 3.2 and spring 3.1.

Thanks in advance!!!

Upvotes: 3

Views: 2391

Answers (2)

jpkroehling
jpkroehling

Reputation: 14061

By default, Hibernate tries to load the contents of the file "import.sql" (or files specified by the property hibernate.hbm2ddl.import_files), if such file is present in the root of the classpath. So, one "solution" is to create a table that holds only one value, and has a unique constraint. When Hibernate tries to load the file, it would then fail to load it for the second time, due to the unique constraint. I have not tested this, but I think it should work.

Now, if that sounds bad for you (it does for me), then I'd recommend taking a look at the code that Hibernate uses to import this file:

https://github.com/hibernate/hibernate-orm/blob/4.1.5.Final/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExport.java#L432

I'd implement this either as a @Singleton @Startup EJB, or as a context listener, or something similar. The idea is to run it every time the app starts. The code would then check if the database is empty, and import the SQL file when needed.

Upvotes: 2

blank
blank

Reputation: 18180

When do you want the table to be populated?

We check the database state on application startup and populate some tables if they are empty using a Spring ContextLoaderListener - something like this:

public class ExampleContextLoaderListener extends ContextLoaderListener {
    private static Log LOG = LogFactory.getLog("ContextLoaderListener");

    public void contextInitialized(final ServletContextEvent event) {

        super.contextInitialized(event);

        final DBService dbService =
            getCurrentWebApplicationContext().getBean(DBService.class);
        if (!db.initalized()) {
            LOG.info("DB empty ... adding new data");
            // etc.
        } else {
            LOG.info("DB already initalized.")
        }

    }
}

Also see how to test if a table is empty.

Upvotes: 0

Related Questions