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 */ 029public class QueryOrderBy implements CloneSupport<QueryOrderBy> { 030 031 private QueryColumn queryColumn; 032 033 private String orderType = SqlConsts.ASC; //asc desc 034 035 private boolean nullsFirst = false; 036 private boolean nullsLast = false; 037 038 protected QueryOrderBy() { 039 } 040 041 public QueryOrderBy(QueryColumn queryColumn, String orderType) { 042 this.queryColumn = queryColumn; 043 this.orderType = orderType; 044 } 045 046 047 public QueryOrderBy(QueryColumn queryColumn) { 048 this.queryColumn = queryColumn; 049 } 050 051 052 public QueryOrderBy nullsFirst() { 053 this.nullsFirst = true; 054 this.nullsLast = false; 055 return this; 056 } 057 058 059 public QueryOrderBy nullsLast() { 060 this.nullsFirst = false; 061 this.nullsLast = true; 062 return this; 063 } 064 065 066 public String toSql(List<QueryTable> queryTables, IDialect dialect) { 067 String sql = queryColumn.toConditionSql(queryTables, dialect) + orderType; 068 if (nullsFirst) { 069 sql = sql + SqlConsts.NULLS_FIRST; 070 } else if (nullsLast) { 071 sql = sql + SqlConsts.NULLS_LAST; 072 } 073 return sql; 074 } 075 076 @Override 077 public QueryOrderBy clone() { 078 try { 079 QueryOrderBy clone = (QueryOrderBy) super.clone(); 080 // deep clone ... 081 clone.queryColumn = ObjectUtil.clone(this.queryColumn); 082 return clone; 083 } catch (CloneNotSupportedException e) { 084 throw FlexExceptions.wrap(e); 085 } 086 } 087 088}