首页 > 解决方案 > 为什么对于只有 2 列的简单表来说,为 JpaRepo 设置参数太慢?

问题描述

我只使用带有 2 个列的简单实体。在我的表中,PK col 是 db 中的 varchar,但实际存储的值是该 col 中的数字,而其他 col 是 int。DB 是 MS SQL Server。而这张表有1.65亿条记录。

表结构:

SECURITY_TAB
varchar(30) SECID PK;
int VERSION;

实体

@Entity
@Table(name = "SECURITY_TAB")
public class Security {

    @Id
    @Column
    private String secid;

    @Column
    private int version;

//... getter n setter n toString
}

存储库

public interface SecurityRepository extends JpaRepository<Security, String> {

    @Query("SELECT s from Security s where secid= :secid")
    Security findSecurityBySecid(@Param("secid") String secid)); //this is slow

    //below is fine.
    //@Query("SELECT s from Security s where secid='1111'")
    //Security findSecurityBySecid();

}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class SecurityTests {

    @Autowired
    private SecurityRepository securityRepository;

    @Test
    public void testSecurityBySecid() {

        Instant start = Instant.now();
        Security security = securityRepository.findSecurityBySecid("1111");
        System.out.println(Duration.between(start, Instant.now()));
            System.out.println(security);
        System.out.println(Duration.between(start, Instant.now()));
    }

}

这个简单的查询需要 20 多秒,而当我运行类似的查询 MS SQL Server Mgmt Studio 或硬编码时,查询结果中的值会以毫秒为单位返回。那么出了什么问题呢?

标签: spring-bootspring-data-jpaprepared-statement

解决方案


能够解决:解决方案是在 jdbc url 中设置此属性:sendStringParametersAsUnicode=false

如果您使用的是 MS SQL 官方驱动程序,则完整示例:jdbc:sqlserver://yourserver;instanceName=yourInstance;databaseName=yourDBName;sendStringParametersAsUnicode=false;

解决方案:从java sql server 查询运行缓慢


推荐阅读