deadbeef deadbeef - 1 year ago 103
Java Question

Perform native SQL Query during Spring startup

I'm using Spring and Hibernate with an automatically generated database (for that I have set

in the JPA configuration properties).

I also have a class annotated
with a
method that is called on application startup after the database has been created or updated. This is where I setup the database with some default data if it's empty (first launch).

I would like to execute some custom native SQL queries at this moment. These queries won't return anything, they're just configuration stuff (like creating additional indexes or extensions).

Currently I'm stuck on creating a
in order to create a new Hibernate
. I've tried auto wiring it, but it doesn't work :

SessionFactory sessionFactory;

Gives me:
Field sessionFactory in ... required a bean of type 'org.hibernate.SessionFactory' that could not be found.

I understand that I probably need to configure it elsewhere, but I don't know where. Several answers on SO use an xml configuration file, but I'm not using any configuration file so I can't do it that way.

Is there a way Spring can create the
with the appropriate configuration ?

Answer Source

You don't even need to access SessionFactory. Please just put your scripts into a file src/main/resources/scripts/myscript.sql. You can then do the following with Spring:

public class Startup {

    private DataSource dataSource;

    public void runNativeSql() {
        ClassPathResource resource = new ClassPathResource("scripts/myscript.sql");
        try(Connection connection = dataSource.getConnection()) {
            ScriptUtils.executeSqlScript(connection, resource);
        } catch (SQLException | ScriptException e) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download