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 */ 016 017package com.mybatisflex.core.activerecord.query; 018 019import com.mybatisflex.core.activerecord.Model; 020import com.mybatisflex.core.field.FieldQueryManager; 021import com.mybatisflex.core.field.QueryBuilder; 022import com.mybatisflex.core.mybatis.MappedStatementTypes; 023import com.mybatisflex.core.query.FieldsBuilder; 024import com.mybatisflex.core.util.LambdaGetter; 025 026import java.io.Serializable; 027import java.util.Collections; 028import java.util.List; 029 030/** 031 * 使用 {@code Fields Query} 的方式进行关联查询。 032 * 033 * @author 王帅 034 * @since 2023-07-30 035 */ 036public class FieldsQuery<T extends Model<T>> extends FieldsBuilder<T> { 037 038 public FieldsQuery(Model<T> model) { 039 super(model); 040 } 041 042 @Override 043 public <F> FieldsQuery<T> fieldMapping(LambdaGetter<F> field, QueryBuilder<F> builder) { 044 super.fieldMapping(field, builder); 045 return this; 046 } 047 048 @Override 049 public <F> FieldsBuilder<T> fieldMapping(LambdaGetter<F> field, boolean prevent, QueryBuilder<F> builder) { 050 super.fieldMapping(field, prevent, builder); 051 return this; 052 } 053 054 protected Object pkValue() { 055 // 懒加载,实际用到的时候才会生成 主键值 056 return ((Model<T>) delegate).pkValue(); 057 } 058 059 /** 060 * 根据主键查询一条数据。 061 * 062 * @return 一条数据 063 */ 064 public T oneById() { 065 List<T> entities = Collections.singletonList(baseMapper().selectOneById((Serializable) pkValue())); 066 FieldQueryManager.queryFields(baseMapper(), entities, fieldQueryMap); 067 return entities.get(0); 068 } 069 070 /** 071 * 根据主键查询一条数据,返回的数据为 asType 类型。 072 * 073 * @param asType 接收数据类型 074 * @param <R> 接收数据类型 075 * @return 一条数据 076 */ 077 @SuppressWarnings("unchecked") 078 public <R> R oneByIdAs(Class<R> asType) { 079 try { 080 MappedStatementTypes.setCurrentType(asType); 081 List<R> entities = Collections.singletonList((R) baseMapper().selectOneById((Serializable) pkValue())); 082 FieldQueryManager.queryFields(baseMapper(), entities, fieldQueryMap); 083 return entities.get(0); 084 } finally { 085 MappedStatementTypes.clear(); 086 } 087 } 088 089}