Shahzad
Shahzad

Reputation: 2073

How to append custom sql to Spring Data JPA insert/update

According to IBM's docs, in order for me to do inserts/updates, I need to append some sql (with NC OR with NONE) to update and insert statements.

I am calling the S save(S entity) method on my CrudRepository to do the save. Is it possible for me to extend this a bit to append the required sql?

I know I can write my own custom insert/update statements, but it would be really nice if I could just append to the sql that gets generated.

Upvotes: 1

Views: 1818

Answers (1)

Shahzad
Shahzad

Reputation: 2073

I've managed to get the desired result by extending Hibernate's EmptyInterceptor and overriding the String onPrepareStatement(String sql) method.

public class MyInterceptor extends EmptyInterceptor {

    @Override
    public String onPrepareStatement(String sql) {
        if (sql.startsWith("insert") || sql.startsWith("update")) {
            sql += " with none";
        }
        return sql;
    }
}

I also had to specify this interceptor in my application.properties:

spring.jpa.properties.hibernate.ejb.interceptor=fully.qualified.name.MyInterceptor

Please note that EmptyInterceptor implements the Interceptor interface, and the onPrepareStatement method has been marked as deprecated in the interface.

It is recommended to use the StatementInspector interface instead, but I couldn't figure out how to set this up using Spring Boot. So if you get that working, please share.

Update

You can specify your implementation of StatementInspector in your application.properties:

spring.jpa.properties.hibernate.session_factory.statement_inspector=fully.qualified.name.MyStatementInspector

Upvotes: 2

Related Questions