如何使用JPA QueryBuilder提供自定义表达式或谓词

时间:2015-02-23 11:29:47

标签: spring postgresql jpa full-text-search eclipselink

我正在使用JPA2(EclipseLink实现)和Spring Data,并使用Specification模式提供过滤器规范。

如何引入将映射到自定义SQL运算符的自定义Expression或Predicate?我特别考虑使用PostgreSQL FTS扩展并添加如下条件:

SELECT ... WHERE ... AND column @@ 'ts query'   

到我的规范实例。

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到:

  1. 如果可以选择切换到Hibernate,有一种方法可以使用Hibernate基础架构:

    对于Hibernate中的HQL http://java-talks.blogspot.co.uk/2014/04/use-postgresql-full-text-search-with-hql.html

    用于将Hibernate实现与JPQL集成 http://metabroadcast.com/blog/hibernate-and-postgres-fts

    基本上,你需要做的是

    • 覆盖您的PostgreSQL方言
    • 使用适当的口译员注册功能
    • 当您需要使用FTS时调用函数
  2. 如果你不能使用Hibernate,你仍然可以通过基本上使用相同的方法来实现,如上所述,但使用EclipseLink细节

    以下是使用EclipseLink https://wiki.eclipse.org/Introduction_to_EclipseLink_Expressions_%28ELUG%29

    进行操作的链接

    基本上你需要做同样的工作人员,但EclipseLink风格

    基于文档,它看起来像这样:

    public class MyDatabasePlatform extends DatabasePlatform {
    
        final private int FTS_ID = Interger.MAX_VALUE;
    
        protected void initializePlatformOperators() {
            super.initializePlatformOperators();
            // Create user-defined function
    
            ExpressionOperator toUpper = new ExpressionOperator();
            fts.setSelector(FTS_ID);
            List args = new ArrayList();
            args.addElement(" @@ to_tsquery(");
            args.addElement(")");
            fts.printAs(args);
            fts.bePrefix();
            fts.setNodeClass(FunctionExpression.class);
    
            // Make it available to this platform only
           ExpressionOperator.registerOperator(FTS_ID, "fts");
           addOperator(fts);
       }
    }
    
    Although I'm not sure about that code, you'll need to test this.