首页 > 解决方案 > Grails 查询强制对字符串参数进行隐式转换

问题描述

我正在运行一个带有字符串参数的简单 grails 查询。查看 SQL Server 探查器中生成的查询时,查询会强制从 nvarchar 到 varchar 的隐式转换,这会导致性能问题。

简单的 Grails 查询:

Book.findByTitle("To Catch A Mocking Bird")

图书领域:

class Book {
    String title
    Date dateCreated
    Date lastUpdated

    static constraints = {
    }
}

SQL 表列(由 Grails 生成):

<table>
  <thead>
    <tr>
      <th>table_name</th>
      <th>column_name</th>
      <th>data_type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>book</td>
      <td>id</td>
      <td>bigint</td>
    </tr>
    <tr>
      <td>book</td>
      <td>version</td>
      <td>bigint</td>
    </tr>
    <tr>
      <td>book</td>
      <td>date_created</td>
      <td>datetime2</td>
    </tr>
    <tr>
      <td>book</td>
      <td>last_updated</td>
      <td>datetime2</td>
    </tr>
    <tr>
      <td>book</td>
      <td>title</td>
      <td>varchar</td>
    </tr>
  </tbody>
</table>

在探查器中查询:

declare @p1 int
set @p1=5
exec sp_prepexec @p1 output,N'@P0 int,@P1 nvarchar(4000)',N'/* criteria query */ select TOP(@P0) this_.id as id1_24_0_, this_.version as version2_24_0_, this_.title as title3_24_0_, this_.date_created as date_cre5_24_0_, this_.last_updated as last_upd7_24_0_, from book this_ where this_.title=@P1                ',1,N'To Catch A Mocking Bird'
select @p1

请注意,参数是字符串“To Catch A Mocking Bird” 。表“title”列的类型是“varchar” sp_prepexec 语句将参数字符串作为 nvarchar(4000)。这会导致隐式转换,这可能会产生负面的性能问题。

由于查询语句是由 Grails 中的 GORM/Hibernate 生成的,因此我无法控制查询语句的创建。

这是一个错误,还是需要设置一些配置,以便语句采用 varchar 而不是 nvarchar?

环境:

  1. 圣杯:3.3.8
  2. 戈姆:6.1.10
  3. 休眠:5.1.5
  4. SQL 服务器:12.0.2269

标签: sql-servergrailsimplicit-conversionvarcharnvarchar

解决方案


您应该配置您的 JDBC 驱动程序。默认情况下,字符串参数将以 Unicode 格式发送到数据库服务器,因此如果您尚未在连接 url 中配置它,它将VARCHARNVARCHAR.

在您的数据源配置中设置sendStringParametersAsUnicode参数。false更多信息在这里


推荐阅读