1

I am using Sping-Boot(2.3.0.RELEASE) with Spring-Data and SQL server with driver 'mssql-jdbc'(8.4.1.jre8) and want to use SQL server FREETEXT() for full-text search in the query from spring boot repository.

I used two approaches to add custom SQL function FREETEXT but got similar errors.

  1. Using Custom Dialect
    public class CustomDialect extends SQLServer2012Dialect {
      public CustomDialect() {
        super();
        registerFunction(
            "FREETEXT",
            new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "FREETEXT((column_name), ?1)"));
      }
    }
  1. Using MetadataBuilderContributor
    public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {
      @Override
      public void contribute(MetadataBuilder metadataBuilder) {
            metadataBuilder.applySqlFunction(
                "FREETEXT",
                new SQLFunctionTemplate(StandardBasicTypes.BOOLEAN, "FREETEXT((column_name), ?1)"));
      }
    }

The repository code looks like this.

    @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);
    }

This function is giving the following error when called

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

When I remove > from the query then it doesn't identify Freetext as a function that is added as a custom SQL function in the Custom dialect or MetadataBuilderContributor. Also, I have tried all the return types in the custom SQL function.

This technique worked in MySQL (Match Against query) as per Registering a SQL function with JPA and Hibernate but not working with MS SQL-Server.

I don't want to use Native Query as it will again result in issues when changing the database

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56
pj2494
  • 111
  • 7

0 Answers0