【问题标题】:Why JPA takes time for transition from close stmt to next Prepare stmt为什么 JPA 需要时间从关闭 stmt 过渡到下一个 Prepare stmt
【发布时间】:2021-03-02 05:40:07
【问题描述】:

我有 JPA 语句,在执行时执行简单查询。

我检查了日志, 它在可接受的时间内执行,但为了执行下一条语句,准备下一条语句需要时间

这里是日志

2021-03-01T12:35:42.008614Z    84 Prepare   SELECT * from table where id=?
2021-03-01T12:35:42.008810Z    84 Execute   SELECT * from table where id=4
2021-03-01T12:35:42.012826Z    84 Close stmt    
2021-03-01T12:35:42.033090Z    84 Prepare   SELECT * from table where id=?
2021-03-01T12:35:42.033279Z    84 Execute   SELECT * from table where id=5
2021-03-01T12:35:42.033860Z    84 Close stmt    
2021-03-01T12:35:42.054576Z    84 Prepare   SELECT * from table where id=?
2021-03-01T12:35:42.054792Z    84 Execute   SELECT * from table where id=6
2021-03-01T12:35:42.055372Z    84 Close stmt    

时间差可能看起来不大但是这条语句要执行1200+次左右,所以最后的延迟实在是太大了

有什么办法可以减少转换时间(关闭语句和下一条准备语句之间的时间)?

中间没有语句或代码行导致任何时间延迟,它是循环中的单个语句

:更新->

我通过在 application.yml 文件中启用 CachePrepStmt 属性来减少转换时间

所以新的转换时间大约是 0.1 毫秒,但现在执行时间是 20 毫秒

怎么会这样,有什么想法吗?

这是新的日志语句

    
2021-03-02T06:20:51.249367Z    59 Execute   SELECT * from table where id=5
2021-03-02T06:20:51.269273Z    59 Reset stmt    
2021-03-02T06:20:51.269385Z    59 Execute   SELECT * from table where id=6
2021-03-02T06:20:51.289372Z    59 Reset stmt    
2021-03-02T06:20:51.289512Z    59 Execute   SELECT * from table where id=7
2021-03-02T06:20:51.308678Z    59 Reset stmt    
2021-03-02T06:20:51.308812Z    59 Execute   SELECT * from table where id=8
2021-03-02T06:20:51.328953Z    59 Reset stmt    
2021-03-02T06:20:51.329123Z    59 Execute   SELECT * from table where id=9
2021-03-02T06:20:51.348447Z    59 Reset stmt    

【问题讨论】:

  • 可以分享代码吗?

标签: java mysql hibernate jpa prepared-statement


【解决方案1】:

首先,看起来您只是使用准备好的语句。这种情况下不需要JPA,只要涉及到JDBC PreparedStatement即可。

其次,您可以像这样使用 `in' 谓词来减少工作量:

SELECT * from table where id in (4, 5, 6, 7, 8, 9)

如果 `id' 是主键或索引字段,这会产生足够快的单选。但不要忘记检查查询的长度是否合理。

另一个选项是选择一个 ID 范围

SELECT * from table where id between 4 and 9

然后根据需要在客户端过滤结果,只需跳过不必要的 id。

【讨论】:

  • 嗨,@S.Kadakov,我更新了问题,你能帮我弄清楚现在执行时间是如何增加的吗? - 谢谢
  • 此时您似乎设法重置了准备好的语句(设置新值会重置该语句),但您仍然没有减少查询次数。尝试减少它,从而降低总执行时间。
  • 我无法减少查询的数量,因为它被用于每次执行,我检查了服务器日志,设置从上述执行获得的值不需要任何时间(大约0.001ms) ,我的主要问题在于减少执行时间
  • 是某种缓存吗?
  • 是的,我通过这个设置cachePrepStmts: true,转换时间显着减少,因为日志中的执行时间增加了但是当我在mysql查询上使用explain analyze时,它显示执行时间是只有大约 0.4-1ms 我不知道剩余时间在哪里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2018-08-21
  • 2013-01-04
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
相关资源
最近更新 更多