How to import initial data to database with Hibernate?

When deploying applications, I often use Hibernate’s capacity to create database schema in order to simplify the deployment. This is easily achievable by configuring hibernate.hbm2ddl.auto property.

However, on occasion I also need to insert some initial data to database, for example root user. Is there a way I could achieve this via hibernate with some kind of load textual file?

I know I could easily program the code that will do so, but just wondering if there is already some utility that can help me achieve the same via configuration?


Solution 1:

I found this by doing a search on "Hibernate fixtures" :

Hibernate will create the database when the entity manager factory is created (actually when Hibernate's SessionFactory is created by the entity manager factory). If a file named import.sql exists in the root of the class path ('/import.sql') Hibernate will execute the SQL statements read from the file after the creation of the database schema. It is important to remember that before Hibernate creates the schema it empties it (delete all tables, constraints, or any other database object that is going to be created in the process of building the schema).

Source: http://www.velocityreviews.com/forums/t667849-hibernate-quotfixturesquot-or-database-population.html

Give it a try and let us know if it works!

Solution 2:

Adding import.sql to the class path works great, hbm2ddl checks if the file exists and executes it. The only additional detail is that each sql command must be on its own line, otherwise it will fail to execute.

This will also work only if hbm2ddl.auto is set to create or create-drop.

Solution 3:

Add hibernate property hibernate.hbm2ddl.import_files in your hibernate configuration. Change hibernate.hbm2ddl.auto property to create. Add initial_data.sql in /classes directory with initial sql code to insert data. Hibernate execute this after create database schema.

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.hbm2ddl.import_files">initial_data.sql</prop>
        </props>
    </property>
</bean>

If you do not want to add a property in your hibernate configuration you can create a file import.sql in /classes directory and hibernate use this by default if property hibernate.hbm2ddl.auto equals to create