Troubleshoot hibernate for SQL Server paging slow

Source: Internet
Author: User

 One, hibernate paging hibernate to MSSQL pseudo-paging
Paging is a Web project in a less than a feature, the amount of data can not be fully displayed when it is necessary to use paging technology. I believe you are not familiar with hibernate in the page:
Java code
    1. Public Query setmaxresults (int maxResults);
    2. Public Query setfirstresult (int firstresult);

As long as the two methods are called and the parameters are set, Hibernate auto-paging completely masks the underlying database paging technology, which is one of the reasons why many developers like hibernate.
A strange problem was encountered in the development of the project. The database uses SQL Server 2005 and the two parameters above, but each SQL statement sent to the database side is select Top .... Statement. Even if you query section 10w, there is only one select top statement, which can cause doubts about hibernate implementing SQL Server paging. Hibernate's paging method for different databases is encapsulated in the corresponding database dialect, and transformed into the corresponding database paging algorithm by getlimitstring method.
Take the dialect mysqldialect of the common MySQL database as an example:
Java code
  1. public string getlimitstring (String sql, Boolean hasoffset) {
  2. return New StringBuffer (sql.length () + )
  3. . append (SQL)
  4. . Append (Hasoffset?  "Limit?,?": "limit?")
  5. . toString ();
  6. }

We use the familiar MySQL limit for paging.
Dialect oracle9idialect for Oracle databases:
Java code
  1. StringBuffer pagingselect = new StringBuffer (sql.length () +100);
  2. if (hasoffset) {
  3. Pagingselect.append ("SELECT * from" (select Row_.*, RowNum rownum_ from (");
  4. }
  5. else {
  6. Pagingselect.append ("select * FROM (");
  7. }
  8. Pagingselect.append (SQL);
  9. if (hasoffset) {
  10. Pagingselect.append (") Row_ where RowNum <=?) Where Rownum_ >? ");
  11. }
  12. else {
  13. Pagingselect.append (") where RowNum <=?");
  14. }

Complete pagination with Oracle's rownum combined with three-tier nested queries. This three-tier is Oracle's most classic and efficient paging algorithm.
However, the dialect sqlserverdialect for SQL Server:
Java code
  1. public string getlimitstring (string queryselect, int offset, int limit) {
  2. if (offset > 0) {
  3. throw New Unsupportedoperationexception ( "Query result offset is not supported");
  4. }
  5. return New StringBuffer (queryselect.length () + 8)
  6. . Append (Queryselect)
  7. . Insert (Getafterselectinsertpoint (queryselect), "top" + limit)
  8. . toString ();
  9. }

Rub the eyes, then rub, yes, only a top statement appears. This means that if you query the data on page 10w, you need to extract all the data from the first 10w pages. Hibernate paging for SQL Server is pseudo-paging, so as the amount of data increases and users complain that the system is slow and the programmer complains that hibernate performance is low, the DBA complains that the developer SQL is too shallow.
Do not know the Hibernate development group, for what is not currently or the situation does not really provide SQL Server paging technology, then we implement it ourselves.
Dialect Category:
Java code
  1. Public class Sqlserver2005dialect extends Sqlserverdialect {
  2. /** 
  3. *
  4. * Do I need to bind the limit parameter?
  5. *
  6. * When using top in SQL Server, you cannot use parameters to represent top bars, while using row_number () you need to supply the limit parameter
  7. */
  8. private Threadlocal<boolean> supportsvariablelimit = new threadlocal<boolean> ();
  9. Public Sqlserver2005dialect () {
  10. Registerfunction ("Bitand", new Bitandfunction ());
  11. Registerfunction ("Bitxor", new Bitxorfunction ());
  12. Registerfunction ("Bitor", new Bitorfunction ());
  13. Setsupportsvariablelimit (false);
  14. }
  15. /** 
  16. *
  17. * <p>
  18. * Sets whether the limit parameter is bound first.
  19. * </p>
  20. *
  21. * @param First
  22. */
  23. private void Setsupportsvariablelimit (boolean first) {
  24. This.supportsVariableLimit.set (boolean.valueof (first));
  25. }
  26. /** 
  27. *
  28. * <p>
  29. * Gets the location of the SELECT clause in SQL.
  30. * </p>
  31. *
  32. * @param sql
  33. *
  34. * @return int
  35. */
  36. protected static int getsqlafterselectinsertpoint (String sql) {
  37. int selectindex = Sql.tolowercase (). IndexOf ("select");
  38. int selectdistinctindex = Sql.tolowercase (). IndexOf ("SELECT distinct");
  39. return Selectindex + ((Selectdistinctindex = = Selectindex)?  : 6);
  40. }
  41. Public Boolean supportslimitoffset () {
  42. return true;
  43. }
  44. /* 
  45. * Hibernate after obtaining the limit String (the limit clause has been added), if this method returns True,
  46. *
  47. * Additional parameter values (Row_number () range) are added (the policy may be: There is offset set two parameter value, no parameter value set)
  48. */
  49. Public Boolean supportsvariablelimit () {
  50. return ((Boolean) this.supportsVariableLimit.get ()). Booleanvalue ();
  51. }
  52. Public Boolean usemaxforlimit () {
  53. return true;
  54. }
  55. /** 
  56. * Home Top, later with Row_number
  57. */
  58. Public string getlimitstring (string query, int offset, int limit) {
  59. Setsupportsvariablelimit (Offset > 0);
  60. if (offset = = 0) {
  61. return New StringBuffer (query.length () + 8). Append (query). Insert (
  62. Getsqlafterselectinsertpoint (query), "top" + limit)
  63. . toString ();
  64. }
  65. return getlimitstring (query, offset > 0);
  66. }
  67. Public string getlimitstring (String sql, Boolean hasoffset) {
  68. int orderbyindex = Sql.tolowercase (). LastIndexOf ("Order by");
  69. if (Orderbyindex <= 0) {
  70. throw New Unsupportedoperationexception (
  71. "must specify ' ORDER BY ' statement-to-support-limit operation with offset in SQL Server 2005");
  72. }
  73. String Sqlorderby = sql.substring (Orderbyindex + 8);
  74. String Sqlremoveorderby = sql.substring (0, Orderbyindex);
  75. int insertpoint = getsqlafterselectinsertpoint (sql);
  76. return New StringBuffer (Sql.length () + + )
  77. . Append ("with Temppagination as (")
  78. . Append (Sqlremoveorderby)
  79. . Insert (
  80. Insertpoint + ,
  81. "Row_number () over (ORDER by" + Sqlorderby
  82. + ") as RowNumber,")
  83. . Append (
  84. ") SELECT * from temppagination where rownumber>? and rownumber<=? ")
  85. . toString ();
  86. }
  87. }


Finally configure dialect to use your own Sqlserver2005dialect class when configuring Hibernate in Hibernate.cfg.xml

<property name= "dialect" > com.common.sqlserver2005dialect</property> or in an integrated configuration file with spring

<prop key= "Hibernate.dialect" >com.common.SQLServer2005Dialect</prop>

When paging, you can achieve very good efficiency.


The first page uses the top page, and later the first page of the Row_number page the above query requires that SQL must contain a sort clause.
This is only the problem that SQL Server encountered during the project process, and you will not experience this problem if you use Mysql,oracle.

Troubleshoot hibernate for SQL Server paging slow

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.