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.relation; 017 018import com.mybatisflex.core.row.Row; 019import com.mybatisflex.core.util.FieldWrapper; 020 021import java.lang.reflect.Field; 022import java.util.List; 023 024public class ToOneRelation<SelfEntity> extends AbstractRelation<SelfEntity> { 025 026 027 public ToOneRelation(String selfField, String targetSchema, String targetTable, String targetField, String valueField, 028 String joinTable, String joinSelfColumn, String joinTargetColumn, 029 String dataSource, Class<SelfEntity> selfEntityClass, Field relationField, 030 String extraCondition,String[] selectColumns) { 031 super(selfField, targetSchema, targetTable, targetField, valueField, 032 joinTable, joinSelfColumn, joinTargetColumn, 033 dataSource, selfEntityClass, relationField, 034 extraCondition, selectColumns 035 ); 036 } 037 038 039 @Override 040 public void join(List<SelfEntity> selfEntities, List<?> targetObjectList, List<Row> mappingRows) { 041 selfEntities.forEach(selfEntity -> { 042 Object selfValue = selfFieldWrapper.get(selfEntity); 043 if (selfValue != null) { 044 selfValue = selfValue.toString(); 045 String targetMappingValue = null; 046 if (mappingRows != null) { 047 targetMappingValue = getTargetMappingValue(mappingRows, selfValue); 048 if (targetMappingValue == null) { 049 return; 050 } 051 } else { 052 targetMappingValue = (String) selfValue; 053 } 054 055 for (Object targetObject : targetObjectList) { 056 Object targetValue = targetFieldWrapper.get(targetObject); 057 if (targetValue != null && targetMappingValue.equals(targetValue.toString())) { 058 if (onlyQueryValueField) { 059 //仅绑定某个字段 060 relationFieldWrapper.set(FieldWrapper.of(targetObject.getClass(), valueField).get(targetObject), selfEntity); 061 } else { 062 relationFieldWrapper.set(targetObject, selfEntity); 063 } 064 break; 065 } 066 } 067 } 068 }); 069 } 070 071 072 private String getTargetMappingValue(List<Row> mappingRows, Object selfValue) { 073 for (Row mappingRow : mappingRows) { 074 if (selfValue.equals(String.valueOf(mappingRow.getIgnoreCase(joinSelfColumn)))) { 075 Object joinValue = mappingRow.getIgnoreCase(joinTargetColumn); 076 if (joinValue != null) { 077 return joinValue.toString(); 078 } 079 } 080 } 081 return null; 082 } 083 084}