hibernate.jdbc.fetch_size 和批量获取策略@BatchSize 的区别

Difference between hibernate.jdbc.fetch_size and batch fetch strategy @BatchSize

对于 Hibernate 中的 N+1 查询问题,我在集合和 class 级别添加了 @BatchSize(size=20)。每次获取 20 条记录时效果很好。 现在我发现有一个 hibernate.jdbc.fetch_size 配置选项,我认为它与 @BatchSize 注释相同。 但是对我在项目中配置时的N+1查询问题没有影响。

我错了 hibernate.jdbc.fetch_size 吗? hibernate.jdbc.fetch_size 有什么用?

hibernate.jdbc.fetch_size是一个JDBC driver configuration,它决定了:

the number of rows fetched when there is more than a one row result on select statements

Hibernate 使用此配置来设置 PreparedStatement.fetchSize 并根据 JDBC 文档:

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet objects genrated by this Statement. If the value specified is zero, then the hint is ignored. The default value is zero.

所以这个设置只是一个提示,它允许 JDBC 驱动程序批量检索选定的行,以最大限度地减少数据库网络往返次数。

@BatchSize 是一个 Hibernate fetching 优化,它控制生成的 SELECT 语句的数量。