SQLServer2005Dialect.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2011-2014, hubin (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.baomidou.mybatisplus.plugins.pagination.dialects;
  17. import com.baomidou.mybatisplus.plugins.pagination.IDialect;
  18. import com.baomidou.mybatisplus.toolkit.StringUtils;
  19. /**
  20. * <p>
  21. * SQLServer 2005 数据库分页方言
  22. * </p>
  23. *
  24. * @author hubin
  25. * @Date 2016-11-10
  26. */
  27. public class SQLServer2005Dialect implements IDialect {
  28. public static final SQLServer2005Dialect INSTANCE = new SQLServer2005Dialect();
  29. private static String getOrderByPart(String sql) {
  30. String loweredString = sql.toLowerCase();
  31. int orderByIndex = loweredString.indexOf("order by");
  32. if (orderByIndex != -1) {
  33. return sql.substring(orderByIndex);
  34. } else {
  35. return "";
  36. }
  37. }
  38. public String buildPaginationSql(String originalSql, int offset, int limit) {
  39. StringBuilder pagingBuilder = new StringBuilder();
  40. String orderby = getOrderByPart(originalSql);
  41. String distinctStr = "";
  42. String loweredString = originalSql.toLowerCase();
  43. String sqlPartString = originalSql;
  44. if (loweredString.trim().startsWith("select")) {
  45. int index = 6;
  46. if (loweredString.startsWith("select distinct")) {
  47. distinctStr = "DISTINCT ";
  48. index = 15;
  49. }
  50. sqlPartString = sqlPartString.substring(index);
  51. }
  52. pagingBuilder.append(sqlPartString);
  53. // if no ORDER BY is specified use fake ORDER BY field to avoid errors
  54. if (StringUtils.isEmpty(orderby)) {
  55. orderby = "ORDER BY CURRENT_TIMESTAMP";
  56. }
  57. StringBuilder sql = new StringBuilder();
  58. sql.append("WITH query AS (SELECT ").append(distinctStr).append("TOP 100 PERCENT ")
  59. .append(" ROW_NUMBER() OVER (").append(orderby).append(") as __row_number__, ").append(pagingBuilder)
  60. .append(") SELECT * FROM query WHERE __row_number__ BETWEEN ")
  61. //FIX#299:原因:mysql中limit 10(offset,size) 是从第10开始(不包含10),;而这里用的BETWEEN是两边都包含,所以改为offset+1
  62. .append(offset + 1)
  63. .append(" AND ")
  64. .append(offset + limit).append(" ORDER BY __row_number__");
  65. return sql.toString();
  66. }
  67. }