【问题标题】:hibernate SQLQueryImpl setParameter vs setString休眠 SQLQueryImpl setParameter vs setString
【发布时间】:2016-07-11 15:09:07
【问题描述】:

我们无法弄清楚为什么在 executeUpdate 查询中使用 setParameter 比使用 setString、setLong 更慢。

  SQLQueryImpl query = session.createSQLQuery("update message set status = :status where attempt_id = :attemptId")

每当我使用时:

query.setParameter("status", Status.DONE)
query.setParameter("attemptId", id)

与使用相比,它的解析速度慢了近 10 倍:

query.setString("status", Status.DONE.toString())
query.setLong("attemptId", id)

我可以验证他们在下面生成了类似的查询:

update message set status = ? where attempt_id = ?

为什么 setParameter() 比较慢?

使用 setString(), setLong() 优先于使用 setParameter()

我认为它只是添加了一个层来确定要添加的类型,但应该几乎相同。

【问题讨论】:

    标签: java hibernate grails


    【解决方案1】:

    检查AbstractQueryImpl 的源代码将揭示原因。简而言之,它必须弄清楚你正在设置的参数Type 是什么,这很昂贵(而且很浪费,因为你应该知道你在注入什么)。

    public Query setParameter(String name, Object val) throws HibernateException {
        if (val == null) {
            Type type = parameterMetadata.getNamedParameterExpectedType( name );
            if ( type == null ) {
                type = StandardBasicTypes.SERIALIZABLE;
            }
            setParameter( name, val, type );
        }
        else {
            // determineType() method below is expensive
            setParameter( name, val, determineType( name, val ) );
        }
    

    现在与setString() 比较,它不必确定Type 而是显式设置它:

    public Query setString(int position, String val) {
        setParameter(position, val, StandardBasicTypes.STRING);
        return this;
    }
    

    使用setString 或setLong 根据方法签名的类型也更严格,这通常是您想要的(最好在编译时失败而不是在运行时失败)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2023-03-28
      • 2013-05-26
      • 2011-05-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多