deadbeef deadbeef - 1 month ago 11
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

"hibernate.hbm2ddl.auto"
to
"update"
in the JPA configuration properties).

I also have a class annotated
@Configuration
with a
@PostConstruct
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
SessionFactory
in order to create a new Hibernate
Session
. I've tried auto wiring it, but it doesn't work :

@Autowired
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
SessionFactory
with the appropriate configuration ?

Answer

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:

@Component
public class Startup {

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void runNativeSql() {
        ClassPathResource resource = new ClassPathResource("scripts/myscript.sql");
        try(Connection connection = dataSource.getConnection()) {
            ScriptUtils.executeSqlScript(connection, resource);
        } catch (SQLException | ScriptException e) {
            //LOG
        }
    }
}
Comments