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 018import com.mybatisflex.core.dialect.IDialect; 019 020import java.io.Serializable; 021import java.util.ArrayList; 022import java.util.List; 023import java.util.function.Supplier; 024 025/** 026 * @author michael yang (fuhai999@gmail.com) 027 * @Date: 2020/1/14 028 */ 029public class Join implements Serializable { 030 031 private static final long serialVersionUID = 1L; 032 033 static final String TYPE_LEFT = " LEFT JOIN "; 034 static final String TYPE_RIGHT = " RIGHT JOIN "; 035 static final String TYPE_INNER = " INNER JOIN "; 036 static final String TYPE_FULL = " FULL JOIN "; 037 static final String TYPE_CROSS = " CROSS JOIN "; 038 039 040 private String type; 041 private QueryTable queryTable; 042 private QueryCondition on; 043 private boolean effective; 044 045 public Join(String type, String table, boolean when) { 046 this.type = type; 047 this.queryTable = new QueryTable(table); 048 this.effective = when; 049 } 050 051 public Join(String type, QueryWrapper queryWrapper, boolean when) { 052 this.type = type; 053 this.queryTable = new SelectQueryTable(queryWrapper); 054 this.effective = when; 055 } 056 057 058 059 QueryTable getQueryTable() { 060 return queryTable; 061 } 062 063 064 public void on(QueryCondition condition) { 065 this.on = condition; 066 } 067 068 QueryCondition getOnCondition(){ 069 return on; 070 } 071 072 public boolean checkEffective() { 073 return effective; 074 } 075 076 public void when(boolean when) { 077 this.effective = when; 078 } 079 080 public void when(Supplier<Boolean> fn) { 081 this.effective = fn.get(); 082 } 083 084 public String toSql(List<QueryTable> queryTables, IDialect dialect) { 085 //left join, right join, inner join ... 086 StringBuilder sql = new StringBuilder(type); 087 sql.append(queryTable.toSql(dialect)); 088 089 //left join xxx as xxx2 on xxx2.id = xxx3.other 090 List<QueryTable> newQueryTables = new ArrayList<>(queryTables); 091 newQueryTables.add(queryTable); 092 sql.append(" ON ").append(on.toSql(newQueryTables, dialect)); 093 return sql.toString(); 094 } 095}