有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么JPA需要时间从关闭stmt过渡到下一个准备stmt

我有一个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多次,因此最终延迟太大

有没有办法缩短转换时间(close语句和下一个prepare语句之间的时间)

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

:更新->

通过在应用程序中启用CachePrepStmt属性,我设法减少了转换时间。yml文件

因此,新的转换时间约为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    

共 (1) 个答案

  1. # 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即可