sql-server - 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?
环境:
- 圣杯:3.3.8
- 戈姆:6.1.10
- 休眠:5.1.5
- SQL 服务器:12.0.2269
解决方案
您应该配置您的 JDBC 驱动程序。默认情况下,字符串参数将以 Unicode 格式发送到数据库服务器,因此如果您尚未在连接 url 中配置它,它将VARCHAR
以NVARCHAR
.
在您的数据源配置中设置sendStringParametersAsUnicode
参数。false
更多信息在这里。
推荐阅读
- r - geom_bar 中的 aes(group = x) 如何计算比例?
- firebase - 更改域时保持用户登录(Firebase 身份验证)
- c++ - 以派生类为参数的 C++ 基类构造函数(?)
- c++ - 使用 args 传递函数并将值返回给另一个函数
- python - 推断指定初始值和最终值的子字符串
- python - Keras 中的 model.predict() 无法正常工作
- c# - C# 使用带有 RadioButton 的 switch 语句
- laravel - Laravel Cashier 付款尝试失败,因为付款方式无效
- c# - 将用户的多个字符串输入转换为 Int、DateTime 和 Decimal 数据类型
- apache-spark - 如何根据 Pyspark 中的值找到前 n 个键?