001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.query; 017 018 019import com.mybatisflex.core.constant.SqlConsts; 020import com.mybatisflex.core.dialect.IDialect; 021import com.mybatisflex.core.exception.FlexExceptions; 022import com.mybatisflex.core.util.ObjectUtil; 023 024import java.util.List; 025 026/** 027 * 排序字段 028 * @author michael 029 */ 030public class QueryOrderBy implements CloneSupport<QueryOrderBy> { 031 032 private QueryColumn queryColumn; 033 034 /** 035 * asc, desc 036 */ 037 private String orderType = SqlConsts.ASC; 038 039 private boolean nullsFirst = false; 040 private boolean nullsLast = false; 041 042 protected QueryOrderBy() { 043 } 044 045 public QueryOrderBy(QueryColumn queryColumn, String orderType) { 046 this.queryColumn = queryColumn; 047 this.orderType = orderType; 048 } 049 050 051 public QueryOrderBy(QueryColumn queryColumn) { 052 this.queryColumn = queryColumn; 053 } 054 055 056 public QueryOrderBy nullsFirst() { 057 this.nullsFirst = true; 058 this.nullsLast = false; 059 return this; 060 } 061 062 063 public QueryOrderBy nullsLast() { 064 this.nullsFirst = false; 065 this.nullsLast = true; 066 return this; 067 } 068 069 070 public String toSql(List<QueryTable> queryTables, IDialect dialect) { 071 String sql = queryColumn.toConditionSql(queryTables, dialect) + orderType; 072 if (nullsFirst) { 073 sql = sql + SqlConsts.NULLS_FIRST; 074 } else if (nullsLast) { 075 sql = sql + SqlConsts.NULLS_LAST; 076 } 077 return sql; 078 } 079 080 081 @Override 082 public QueryOrderBy clone() { 083 try { 084 QueryOrderBy clone = (QueryOrderBy) super.clone(); 085 // deep clone ... 086 clone.queryColumn = ObjectUtil.clone(this.queryColumn); 087 return clone; 088 } catch (CloneNotSupportedException e) { 089 throw FlexExceptions.wrap(e); 090 } 091 } 092 093}