我的数据库中有一张表映射到我的项目中的一个实体。我正在尝试根据该实体的 PK 使用
findById()
执行简单的选择。该表有 4800 万行,因此它是一个非常重的表。 Hibernate 生成一个简单的 SELECT 语句来执行此操作。问题是这个简单的 SELECT 平均需要 3 秒才能运行,但如果我得到相同的查询并在 DBeaver 或 MSSQL 中运行它,则运行时间不到 80 毫秒。造成这个问题的原因可能是什么?
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "MyEntity")
public class MyEntity implements Serializable {
@EmbeddedId
private IdMyEntity id;
// More columns
@Data
@Builder
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
public static class IdMyEntity implements Serializable {
// 7 columns that represent the PK of the entity
}
}
select
-- All the columns from the entity
from
MyEntity myEntity0_
where
-- All the columns that represent the PK of the entity
事实证明,问题是因为我们的 API 将编码为 Unicode 的参数发送到数据库,而列类型为 VARCHAR。因此,表的索引被忽略,因此在获取期间正在扫描整个表。
将
sendStringParametersAsUnicode=false
添加到我们的 JDBC URL 解决了问题。
更多详情可以在这里找到: