Hibernate is 1000 times slower than sql query

后端 未结 2 471
灰色年华
灰色年华 2020-12-16 22:30

I have this setup

@Table(name =\"A\")
EntityA {
    Long ID;
    List children;
}

@Table(name =\"B\")
EntityB {
    Long ID;
    EntityA pare         


        
相关标签:
2条回答
  • 2020-12-16 23:10

    I finally managed to get to the bottom of this. The problem was being caused by Hibernate setting the parameters separately from the actual SQL query that involved subqueries. So native SQL or not, the performance will be slow if this is done. For example this will be slow:

    String sql = some sql that has named parameter = :value
    SQLQuery sqlQuery = session.createSQLQuery(sql);
    sqlQuery.setParameter ("value", someValue);
    List<Object[]> list = (List<Object[]>)sqlQuery.list();
    

    And this will be fast

    String sql = some native sql where parameter = 'actualValue'
    SQLQuery sqlQuery = session.createSQLQuery(sql);
    List<Object[]> list = (List<Object[]>)sqlQuery.list();
    

    It seems that for some reason with letting Hibernate take care of the parameters it ends up getting stuck in the resultSet fetching. This is probably because the underlying query on the database is taking much longer being parameterized. I ended up writing the equivalent of Hibernate Criteria and Restrictions code that sets the parameters directly as above.

    0 讨论(0)
  • 2020-12-16 23:13

    We noticed a similar behaviour in our system.

    And also encountered that writing the query with hardcoded parameters instead of using setParameter() would fixed the issue.

    We are using MS SQL Server and after further investigation we noticed the the root cause of our issue is a default configuration of the sql server driver that transmits the query parameters as unicode. This lead to our indices being ignored since they were based on the ascii values on the queried columns.

    The solution was to setup this property in the jdbc url : sendStringParametersAsUnicode=false

    More details can be found here. https://stackoverflow.com/a/32867579

    0 讨论(0)
提交回复
热议问题