如何在spring data jpa@query中使用sqlserver'freetext'?

bqujaahr  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(265)

我正在使用带有spring数据的spingboot(2.3.0.release)和带有驱动程序“mssqljdbc”(8.4.1.jre8)的sqlserver,并希望使用sqlserver FREETEXT() 在spring启动存储库的查询中进行全文搜索。
我使用了两种方法来添加自定义sql函数 FREETEXT 但也有类似的错误。
使用习惯方言

public class CustomDialect extends SQLServer2012Dialect {
      public CustomDialect() {
        super();
        registerFunction(
            "FREETEXT",
            new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "FREETEXT((column_name), ?1)"));
      }
    }

使用metadatabuildercontributor

public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {
      @Override
      public void contribute(MetadataBuilder metadataBuilder) {
            metadataBuilder.applySqlFunction(
                "FREETEXT",
                new SQLFunctionTemplate(StandardBasicTypes.BOOLEAN, "FREETEXT((column_name), ?1)"));
      }
    }

存储库代码如下所示。

@Repository
    public interface TestRepository extends JpaRepository<TestEntity, String> {

      /**
       * This function uses custom SQL function defined in
       * utility/SqlFunctionsMetadataBuilderContributor.java
       *
       * <p>This function performs search on test table with the query provided for the specific
       * attributes which are configured in the custom sql function
       *
       * @param query the query
       * @return the list
       */

        @Query(
          value =
              "SELECT distinct new com.*.*.*.model.TestModel(t.id, t.name, t.number) "
                  + "FROM TestEntity t WHERE function('FREETEXT', :query)>0 and t.number is not null")
        List<TestModel> findByName(String query);
    }

调用此函数时出现以下错误

o.h.e.j.s.SqlExceptionHelper             : SQL Error: 102, SQLState: S0001
o.h.e.j.s.SqlExceptionHelper             : Incorrect syntax near '>'.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

当我移除 > 从查询中,它不会将freetext标识为在自定义方言或metadatabuildercontributor中作为自定义sql函数添加的函数。此外,我还尝试了自定义sql函数中的所有返回类型。
这种技术在mysql中有效 (Match Against query) 按照在jpa和hibernate中注册sql函数,但不使用mssqlserver。
我不想使用本机查询,因为它在更改数据库时会再次导致问题

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题