All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.querydsl.sql.RelationalPathUtils Maven / Gradle / Ivy

There is a newer version: 6.10.1
Show newest version
/*
 * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.querydsl.sql;

import com.querydsl.core.types.Expression;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Projections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * {@code RelationalPathUtils} provides static utility methods for {@link RelationalPath} instances
 *
 * @author tiwe
 */
@SuppressWarnings("unchecked")
public final class RelationalPathUtils {

  public static  FactoryExpression createProjection(RelationalPath path) {
    if (path.getType().equals(path.getClass())) {
      throw new IllegalArgumentException(
          "RelationalPath based projection can only be used with generated Bean types");
    }
    try {
      // ensure that empty constructor is available
      path.getType().getConstructor();
      return createBeanProjection(path);
    } catch (NoSuchMethodException e) {
      // fallback to constructor projection
      return createConstructorProjection(path);
    }
  }

  private static  FactoryExpression createConstructorProjection(RelationalPath path) {
    Expression[] exprs = path.getColumns().toArray(new Expression[0]);
    return Projections.constructor((Class) path.getType(), exprs);
  }

  private static  FactoryExpression createBeanProjection(RelationalPath path) {
    Map> bindings = new LinkedHashMap<>();
    for (Path column : path.getColumns()) {
      bindings.put(column.getMetadata().getName(), column);
    }
    if (bindings.isEmpty()) {
      throw new IllegalArgumentException("No bindings could be derived from " + path);
    }
    return Projections.fields((Class) path.getType(), bindings);
  }

  private RelationalPathUtils() {}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy