如何将自定义sql附加到Spring Data JPA插入/更新

问题描述 投票:0回答:1

根据IBM's docs,为了让我做插入/更新,我需要附加一些sql(with NCwith NONE)来更新和插入语句。

我在我的CrudRepository上调用S save(S entity)方法来进行保存。我可以扩展这一点来附加所需的sql吗?

我知道我可以编写自己的自定义插入/更新语句,但如果我可以追加到生成的sql那将是非常好的。

spring db2 spring-data spring-data-jpa db2-400
1个回答
0
投票

通过扩展Hibernate的EmptyInterceptor并覆盖String onPrepareStatement(String sql)方法,我设法得到了理想的结果。

public class MyInterceptor extends EmptyInterceptor {

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

我还必须在我的application.properties中指定这个拦截器:

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

请注意,EmptyInterceptor实现了Interceptor接口,并且onPrepareStatement方法已在界面中标记为已弃用。

建议使用StatementInspector接口,但我无法弄清楚如何使用Spring Boot设置它。所以,如果你能做到这一点,请分享。

更新

您可以在StatementInspector中指定application.properties的实现:

spring.jpa.properties.hibernate.session_factory.statement_inspector=fully.qualified.name.MyStatementInspector
© www.soinside.com 2019 - 2024. All rights reserved.