java 如何使用 Hibernate 调用自定义数据库函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1909315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:27:52  来源:igfitidea点击:

How can you call custom database functions with Hibernate?

javasqlhibernatehql

提问by jsight

If I were to define some function in the database (perhaps Postgres, or any other database):

如果我要在数据库中定义一些函数(可能是 Postgres 或任何其他数据库):

create or replace function isValidCookie(ckie);

I would call it from SQL as:

我会从 SQL 调用它:

select * from cookietable c where isValidCookie(c.cookie);

How can I call a custom function such as this from Hibernate?

如何从 Hibernate 调用这样的自定义函数?

采纳答案by ChssPly76

If you want to use your custom function in HQL, you'll need to define it in appropriate Dialect

如果你想在 HQL 中使用你的自定义函数,你需要在适当的方言中定义它

Take a look at PostgreSQLDialect(or any other, really) source, and you'll see a bunch of registerFunction()calls. You'll need to add one more :-) - for your own custom function.

看看PostgreSQLDialect(或任何其他真正的)源,你会看到一堆registerFunction()调用。您需要再添加一个 :-) - 用于您自己的自定义函数。

You'll then have to specify your own dialect in Hibernate configuration.

然后,您必须在 Hibernate 配置中指定您自己的方言。

回答by Trevor Robinson

As of Hibernate 5, if you don't want to depend on or customize the dialect, you can define a MetadataBuilderInitializer. For example, to use MySQL DATE_ADDwith an INTERVALfrom HQL, you can define a custom function called date_add_interval:

从 Hibernate 5 开始,如果您不想依赖或自定义方言,您可以定义一个MetadataBuilderInitializer. 例如,要将 MySQLDATE_ADDINTERVALfrom HQL一起使用,您可以定义一个名为 的自定义函数date_add_interval

public class DateAddIntervalMetadataBuilderInitializer
        implements MetadataBuilderInitializer {
    @Override
    public void contribute(MetadataBuilder metadataBuilder,
            StandardServiceRegistry serviceRegistry) {
        metadataBuilder.applySqlFunction("date_add_interval",
            new SQLFunctionTemplate(DateType.INSTANCE,
                "DATE_ADD(?1, INTERVAL ?2 ?3)"));
    }
}

You would also need to put the name of the class in a JAR resource file called META-INF/services/org.hibernate.boot.spi.MetadataBuilderInitializer.

您还需要将类的名称放在名为 .jar 的 JAR 资源文件中META-INF/services/org.hibernate.boot.spi.MetadataBuilderInitializer

This approach is particularly useful when using Hibernate via a framework such as JPA and/or Spring, where the configuration is performed implicitly by the framework.

这种方法在通过框架(如 JPA 和/或 Spring)使用 Hibernate 时特别​​有用,其中配置由框架隐式执行。