<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 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

      https://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 <%= entityAbsolutePackage %>.service<% if (serviceImpl || multiModule) { %>.impl<% } %>;

<%_
const serviceClassName = entityClass + 'QueryService' + ((serviceImpl || multiModule) ? 'Impl' : '');
const instanceType = restClass;
const pageOrFlux = reactive ? 'Flux' : (ormTool !== 'mybatis' ? 'Page' : 'IPage');
const mapper = entityInstance  + 'Mapper';
const entityListToDto = mapper + '.' + 'toDto';
const entityToDtoReference = mapper + '::'+ 'toDto';
const repository = entityInstance  + 'Repository';
const criteria = entityClass + 'Criteria';
const pageName = ormTool !== 'mybatis' ? 'Page' : 'IPage';
const pageType = ormTool !== 'mybatis' ? 'Pageable' : `Page<${entityClass}>`;
const specificationType = ormTool !== 'mybatis' ? 'Specification' : 'QueryWrapper';
const specificationInstance = ormTool !== 'mybatis' ? 'specification' : 'queryWrapper';
const beans = [];
// add by begcode start
const ignoreRelationshipsOfTree = new Set();
const ignoreRelationshipsOfOther = new Set();
const staticImportPackages = new Set();
staticImportPackages.add(entityAbsolutePackage);
let relationshipParentIdName = '';
let relationshipParentName = '';
const dtoRelationships = dtoReferences.filter(reference => reference.relationship);
const dtoChildrenRelationshipsName = dtoRelationships
        .filter(reference => reference.leafOfTree)
        .map(reference => reference.name);
(dtoChildrenRelationshipsName || []).forEach(dtoRel => {
    ignoreRelationshipsOfOther.add(dtoRel);
});
for (relationship of relationships) {
    staticImportPackages.add(relationship.otherEntity.entityAbsolutePackage);
    if (relationship.otherRelationship && relationship.relationshipRightSide && relationship.otherRelationship.bcConfig && relationship.otherRelationship.bcConfig.leftUnidirectional) {
        ignoreRelationshipsOfTree.add(relationship.relationshipName);
        if (!(relationship.bcConfig.rightHideInList && relationship.bcConfig.leftRelateByIdEntity)) {
            ignoreRelationshipsOfOther.add(relationship.relationshipName);
        }
    }
    if (dtoChildrenRelationshipsName && !dtoChildrenRelationshipsName.includes(relationship.relationshipName)) {
        if (relationship.otherEntity.entityNameCapitalized === entityNameCapitalized && (relationship.relationshipType === 'many-to-one' || relationship.relationshipType === 'one-to-one') && !(relationship.bcConfig && relationship.bcConfig.unidirectionSkip)) {
            relationshipParentIdName = relationship.relationshipName + this._.upperFirst(relationship.otherEntity.primaryKey.name);
            relationshipParentName = relationship.relationshipName;
            ignoreRelationshipsOfTree.add(relationship.relationshipName);
        }
    }
}
staticImportPackages.delete(entityAbsolutePackage);
const filterRelationships = entityJavaFilterableProperties.filter(property => !property.filedName && property.relationshipType);
let filterFields = fields.filter(field => !field.transient).filter(field => !field.options || (!field.options.skipCriteria && !field.options.skipDto ));
if (softDelete) {
    filterFields = (filterFields.filter(field => field.fieldName !== 'delFlag'));
}
if (useMultiTenant) {
    filterFields = (filterFields.filter(field => field.fieldName !== 'tenantId'));
}
let uniqueFieldTypes = Array.from(new Set(filterFields.filter(field => field.filterableField).map(field => field.fieldType)));
if (primaryKey.type === 'String') {
    if (!uniqueFieldTypes.includes('String')) {
        uniqueFieldTypes.push('String');
    }
} else {
    if (!uniqueFieldTypes.includes('Long')) {
        uniqueFieldTypes.push('Long');
    }
}
uniqueFieldTypes = uniqueFieldTypes.filter(type => ['Integer', 'Long', 'Float', 'Double', 'BigDecimal', 'LocalDate', 'ZonedDateTime', 'Instant', 'Duration'].includes(type));
    // add by begcode end
_%>
import java.util.*;
<%_ if (ormTool === 'hibernate') { _%>

import jakarta.persistence.criteria.*;
import jakarta.persistence.*;
import org.hibernate.transform.Transformers;
<%_ } _%>

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tech.jhipster.service.<%= ormTool === 'mybatis' ? 'mybatis.' : '' %>QueryService;

import <%= entityAbsolutePackage %>.domain.<%= persistClass %>;
<%_ if (ormTool === 'hibernate') { _%>
import <%= entityAbsolutePackage %>.domain.*; // for static metamodels
  <%_ staticImportPackages.forEach(staticPackage => { _%>
import <%= staticPackage %>.domain.*; // for static metamodels
  <%_ }); _%>
<%_ } _%>

import <%= entityAbsolutePackage %>.repository.<%= entityClass %>Repository;
<%_ if (searchEngineElasticsearch) { _%>
import <%= entityAbsolutePackage %>.repository.search.<%= entityClass %>SearchRepository;
<%_ } _%>
import <%= entityAbsolutePackage %>.service.criteria.<%= entityClass %>Criteria;
<%_ if (dtoMapstruct) { _%>
import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>;
import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper;
<%_ } _%>
<%# add by begcode start %>
import tech.jhipster.service.filter.*;
<%_ if (ormTool === 'mybatis') { %>
import com.diboot.core.binding.Binder;
  <%_ if (fieldsContainParentAndChildren) { _%>
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import java.util.stream.Collectors;
  <%_ } _%>
import tech.jhipster.service.mybatis.CriteriaUtil;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diboot.core.binding.query.BindQuery;
import com.diboot.core.binding.query.dynamic.DynamicJoinQueryWrapper;
<%_ } else { _%>
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import <%= packageName %>.util.JpaUtil;
import <%= packageName %>.util.CriteriaUtil;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ObjectUtils;
<%_ } _%>
import cn.hutool.core.bean.BeanUtil;
import com.google.common.base.CaseFormat;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
<%_
const moduleNameSet = new Set();
otherModuleEntities.forEach(otherModuleEntity => moduleNameSet.add(otherModuleEntity.moduleName));
        for (const importModuleName of moduleNameSet ) {
_%>
// import <%= packageName %><%= importModuleName ? '.' + importModuleName : ''%>.domain.*;
<%_ } _%>
<%_ if (entityClass === 'CommonBigDecimal' || uniqueFieldTypes.includes('BigDecimal')) { _%>
import java.math.BigDecimal;
<%_ } _%>
<%_
const addMethodWithAnnotations = {};
if (annotations && Object.keys(annotations).length > 0) {
    Object.keys(annotations).forEach(optionKey => {
        if (optionKey.startsWith('findAllBy')) {
            addMethodWithAnnotations[optionKey] = annotations[optionKey];
        }
        if (optionKey.startsWith('findOneBy')) {
            addMethodWithAnnotations[optionKey] = annotations[optionKey];
        }
    });
}
_%>
<%_ Object.keys(addMethodWithAnnotations).forEach(addKey => {
    const params = addMethodWithAnnotations[addKey];
    const paramFieldNames = params.split('-');
    paramFieldNames.forEach(fieldName => {
        fields.forEach(field => { _%>
            <%_  if (fieldName === field.fieldName && !field.id) { _%>
              <%_  if (field.fieldIsEnum) { _%>
import <%= packageName %>.domain.enumeration.<%= field.fieldType %>;
              <%_ } _%>
              <%_  if (field.fieldType === 'BigDecimal') { _%>
import java.math.BigDecimal;
              <%_ } _%>
              <%_  if (['LocalDate', 'ZonedDateTime', 'Instant', 'Duration'].includes(field.fieldType)) { _%>
import java.time.<%= field.fieldType %>;
              <%_ } _%>
            <%_ } _%>
<%_        });
    });
_%>
<%_ }); _%>
<%_ if (addCustomMethod.indexOf('queryService') !== -1) { _%>
<%- include(`../../_entityCustom_/${entityClass}.queryService.ejs`, {position: 'import'}); -%>
<%_ } _%>
import static tech.jhipster.service.<%= ormTool === 'mybatis' ? 'mybatis.' : '' %>AggregateUtil.buildAggregate;
import static tech.jhipster.service.<%= ormTool === 'mybatis' ? 'mybatis.' : '' %>AggregateUtil.buildGroupBy;
<%# add by begcode end %>


/**
<%_ if ((enableTranslation && nativeLanguage === 'zh-cn') || !enableTranslation ) { _%>
 * 用于对数据库中的{@link <%= persistClass %>}实体执行复杂查询的Service。
 * 主要输入是一个{@link <%= entityClass %>Criteria}，它被转换为{@link <%= specificationType %>}，
 * 所有字段过滤器都将应用到表达式中。
 * 它返回满足条件的{@link <%= instanceType %>}列表{@link List} 或 {@link <%= instanceType %>} 的分页列表 {@link Page}。
<%_ } else { _%>
 * Service for executing complex queries for {@link <%= persistClass %>} entities in the database.
 * The main input is a {@link <%= entityClass %>Criteria} which gets converted to {@link <%= specificationType %>},
 * in a way that all the filters must apply.
 * It returns a {@link <% if (paginationNo) { %>List<% } else { %>Page<% } %>} of {@link <%= instanceType %>} which fulfills the criteria.
<%_ } _%>
 */
@Service
<%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
@Transactional(readOnly = true)
<%_ } _%>
public class <%= serviceClassName %><% if (serviceImpl || multiModule) { %> extends <%= persistClass %>QueryService<% } else { %> <%= ormTool === 'hibernate' ? 'extends' : 'implements'%> QueryService<<%= persistClass %>><% } %> {

    private static final Logger LOG = LoggerFactory.getLogger(<%= serviceClassName %>.class);
<%_ if (addCustomMethod.indexOf('queryService') !== -1) { _%>
<%- include(`../../_entityCustom_/${entityClass}.queryService.ejs`, {position: 'field'}); -%>
<%_ } _%>
<%- include('../_partials_entity_/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: false, mapsIdAssoc: null, isController: false, beans}); -%>

    /**
     * Return a {@link List} of {@link <%= instanceType %>} which matches the criteria from the database.
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching entities.
     */
    <% if (ormTool === 'hibernate') { %>@Transactional(readOnly = true)<% } %>
    public List<<%= instanceType %>> findByCriteria(<%= criteria %> criteria) {
        LOG.debug("find by criteria : {}", criteria);
        final <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
  <%_ if (dtoMapstruct) { _%>
        return <%= entityListToDto %>(<% if (ormTool === 'hibernate') { %><% if (containsBagRelationships) { %><%= repository %>.fetchBagRelationships(<% } %><%= repository %>.findAll(specification)<% if (containsBagRelationships) { %>)<% } %><% } else { %>Binder.joinQueryList(<%= specificationInstance %>, <%= persistClass %>.class)<% } %>);
  <%_ } else { _%>
        return <% if (ormTool === 'hibernate') { %><% if (containsBagRelationships) { %><%= repository %>.fetchBagRelationships(<% } %><%= repository %>.findAll(<%= specificationInstance %>)<% if (containsBagRelationships) { %>)<% } %><% } else { %>Binder.joinQueryList(<%= specificationInstance %>, <%= persistClass %>.class)<% } %>;
  <%_ } _%>
    }
<%_ if (softDelete && !skipSoftDelete) { _%>

    /**
     * Return a {@link <%= pageName%>} of {@link <%= instanceType %>} which matches the criteria from the database.
     * @param criteria The object which holds all the filters, which the entities should match.
     * @param page The page, which should be returned.
     * @return the matching entities.
     */
    <% if (ormTool === 'hibernate') { %>@Transactional(readOnly = true)<% } %>
    public <%= pageName%><<%= instanceType %>> findByCriteriaInRecycleBin(<%= criteria %> criteria, <%- pageType%> page) {
        LOG.debug("find by criteria : {}, page: {}", criteria, page);
        final <%= specificationType%><<%= persistClass %>> <%= specificationInstance%> = create<%= specificationType%>(criteria)<% if (ormTool === 'hibernate') { %>.and(buildSpecification(new BooleanFilter().setEquals(true),<%= persistClass %>_.delFlag))<% } %>;
  <%_ if (dtoMapstruct) { _%>
        return <%= repository %>.<% if (ormTool === 'hibernate') { %>findAll(specification, page)<% } else { %>selectPageInRecycleBin(page, <%= specificationInstance %>)<% } %>
            .<%= ormTool === 'hibernate' ? 'map' : 'convert'%>(<%= entityToDtoReference %>);
  <%_ } else { _%>
        return <%= repository %>.<% if (ormTool === 'hibernate') { %>findAll(<%= specificationInstance%>, page)<% } else { %>selectPageInRecycleBin(page, <%= specificationInstance %>)<% } %>;
  <%_ } _%>
    }
<%_ } _%>

    /**
     * Return a {@link <%= pageName %>} of {@link <%= instanceType %>} which matches the criteria from the database.
     * @param criteria The object which holds all the filters, which the entities should match.
     * @param page The page, which should be returned.
     * @return the matching entities.
     */
    <% if (ormTool === 'hibernate') { %>@Transactional(readOnly = true)<% } %>
    public <%= pageName %><<%= instanceType %>> findByCriteria(<%= criteria %> criteria, <%- pageType %> page) {
        LOG.debug("find by criteria : {}, page: {}", criteria, page);
        final <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
  <%_ if (ormTool === 'hibernate') { _%>
  <%_ if (dtoMapstruct) { _%>
        return <% if (containsBagRelationships) { %><%= repository %>.fetchBagRelationships(<% } %><%= repository %>.findAll(specification, page)<% if (containsBagRelationships) { %>)<% } %>
            .map(<%= entityToDtoReference %>);
  <%_ } else { _%>
        return <% if (containsBagRelationships) { %><%= repository %>.fetchBagRelationships(<% } %><%= repository %>.findAll(specification, page)<% if (containsBagRelationships) { %>)<% } %>;
  <%_ } _%>
  <%_ } else { _%>
  <%_ if (dtoMapstruct) { _%>
        return Binder.joinQueryPage(<%= specificationInstance %>, <%= persistClass%>.class, page)
            .convert(
                <%= entityInstance %> -> {
                    Binder.bindRelations(<%= entityInstance %>, new String[] {<%- [...ignoreRelationshipsOfOther].map(ignoreRel => `"${ignoreRel}"`).join(', ') %>});
                    return <%= mapper %>.toDto(<%= entityInstance %>);
                }
            );
  <%_ } else { _%>
        return <%= repository %>.selectPage(page, <%= specificationInstance %>);
  <%_ } _%>
  <%_ } _%>
    }

    /**
     * Return the number of matching entities in the database.
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the number of matching entities.
     */
    <% if (ormTool === 'hibernate') { %>@Transactional(readOnly = true)<% } %>
    public long countByCriteria(<%= criteria %> criteria) {
        LOG.debug("count by criteria : {}", criteria);
        <%_ if (ormTool === 'hibernate') { _%>
        final <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
        return <%= repository %>.<%= ormTool === 'hibernate' ? 'count' : 'selectCount'%>(<%= specificationInstance %>);
        <%_ } else { _%>
        return <%= repository %>.selectCount(createQueryWrapperNoJoin(criteria));
        <%_ } _%>
    }
<%_ if (ormTool === 'hibernate') { _%>
    /**
     * Function to convert {@link <%= criteria %>} to a {@link <%= specificationType %>}
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching {@link <%= specificationType %>} of the entity.
     */
    protected <%= specificationType %><<%= persistClass %>> create<%= specificationType %>(<%= criteria %> criteria) {
        <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = Specification.where(null);
        if (criteria != null) {
            // This has to be called first, because the distinct method returns null
            if (criteria.getDistinct() != null) {
                specification = specification.and(distinct(criteria.getDistinct()));
            }
            if (criteria.get<%= primaryKey.nameCapitalized %>() != null) {
                specification = specification.and(<%= primaryKey.javaBuildSpecification %>(criteria.get<%= primaryKey.nameCapitalized %>(), <%= persistClass %>_.<%= primaryKey.name %>));
            }
            if (StringUtils.isNotEmpty(criteria.getJhiCommonSearchKeywords())) {
                if (StringUtils.isNumeric(criteria.getJhiCommonSearchKeywords())) {
                    <%= specificationInstance %> = CriteriaUtil.build(true, <%= specificationInstance %>, buildSpecification(<%_ if (primaryKey.type === 'String' || primaryKey.type === 'UUID') { _%>new <%= primaryKey.type %>Filter().setEquals(<% if (primaryKey.type === 'UUID') { %>UUID.fromString(criteria.getJhiCommonSearchKeywords())<% } else { %>criteria.getJhiCommonSearchKeywords()<% } %><%_ } else { _%>new LongFilter().setEquals(Long.valueOf(criteria.getJhiCommonSearchKeywords())<%_ } _%>), <% if (ormTool !== 'mybatis') { %><%= persistClass %>_.<%= primaryKey.name %>)<% } else {%>"<%= primaryKey.name %>")<% } %>);
                    <%_
                    filterFields.filter((field) => ['Integer', 'Long', 'Float', 'Double', 'BigDecimal', 'Duration'].includes(field.fieldType))
                        .forEach((field) => { _%>
                    <%= specificationInstance %> = CriteriaUtil.build(true, <%= specificationInstance %>, <%= field.fieldJavaBuildSpecification %>(
                        (<%= field.fieldType %>Filter)new <%= field.fieldType %>Filter().setEquals(<%= field.fieldType %>.valueOf(<% if (entityClass === 'CommonBigDecimal' && field.fieldType=== 'BigDecimal') { %>Double.parseDouble(criteria.getJhiCommonSearchKeywords())<% } else { %>criteria.getJhiCommonSearchKeywords()<% }%>)), <% if (ormTool !== 'mybatis') { %><%= persistClass %>_.<%= field.fieldName %>)<% } else {%>"<%= field.columnName %>")<% } %>);
                    <%_
                    });  _%>
                } else {
                    <%_ filterFields.filter((field) => ['String'].includes(field.fieldType)).forEach((field) => { _%>
                    <%= specificationInstance %> = CriteriaUtil.build(true, <%= specificationInstance %>, <%= field.fieldJavaBuildSpecification %>(
                        new StringFilter().setContains(criteria.getJhiCommonSearchKeywords()), <% if (ormTool !== 'mybatis') { %><%= persistClass %>_.<%= field.fieldName %>)<% } else {%>"<%= field.columnName %>")<% } %>);
                    <%_ }); _%>
                }
            } else {
                if (criteria.get<%= primaryKey.nameCapitalized %>() != null) {
                    <%_ const primaryKeyField = fields.find(field => field.name = primaryKey.name); _%>
                    <%_ if (primaryKeyField) { _%>
                    <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, <%= primaryKeyField.fieldJavaBuildSpecification %>(criteria.get<%= primaryKey.nameCapitalized %>(), <% if (ormTool !== 'mybatis') { %><%= persistClass %>_.<%= primaryKey.name %>)<% } else {%>"<%= primaryKey.name %>")<% } %>);
                    <%_ } _%>
                }
                <%_
                filterFields.forEach((field) => {
                  if (field.id || field.transient) return;
                  if (field.filterableField) { _%>
            if (criteria.get<%= field.fieldInJavaBeanMethod %>() != null) {
                specification = specification.and(<%= field.fieldJavaBuildSpecification %>(criteria.get<%= field.fieldInJavaBeanMethod %>(), <%= persistClass %>_.<%= field.fieldName %>));
            }
                <%_ }});
                    relationships.filter(relationship => !(relationship.relationshipRightSide && relationship.bcConfig.leftRelateByIdEntity)).forEach((relationship) => {
                      const bcConfig = relationship.bcConfig || {};
                      if (!bcConfig.unidirectionSkip ) {
                      const metamodelFieldName = (relationship.relationshipManyToMany || relationship.relationshipOneToMany) ? relationship.relationshipFieldNamePlural : relationship.relationshipFieldName; _%>
                <%_ if (((applicationTypeMonolith || applicationTypeMicroservice) && multiModule && moduleName && moduleName !== relationship.otherEntity.moduleName) ||
                     (applicationTypeMicroservice && !(relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName)))) { _%>
                if (criteria.get<%= relationship.relationshipNameCapitalized %>Id() != null) {
                    <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %>Id(),<%= persistClass %>_.<%= relationship.relationshipName %>Id));
                }
                    <%_ if (relationship.otherEntityField) { _%>
                if (criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(relationship.otherEntityField)%>() != null) {
                    <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(relationship.otherEntityField) %>(),<%= persistClass %>_.<%= relationship.relationshipName %><%= this._.upperFirst(relationship.otherEntityField) %>));
                }
                    <%_ } _%>
                <%_ } else { _%>
            if (criteria.get<%= relationship.relationshipNameCapitalized %>Id() != null) {
                <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %>Id(),
                    root -> root.join(<%= persistClass %>_.<%= metamodelFieldName %>, JoinType.LEFT).get(<%= relationship.otherEntity.persistClass %>_.<%= relationship.otherEntity.primaryKey.name %>)));
            }
                    <%_ if (relationship.otherEntityField) { _%>
            if (criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(relationship.otherEntityField)%>() != null) {
                <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(relationship.otherEntityField) %>(),
                    root -> root.join(<%= persistClass %>_.<%= metamodelFieldName %>, JoinType.LEFT).get(<%= relationship.otherEntity.persistClass %>_.<%= relationship.otherEntityField %>)));
            }
                    <%_ } _%>
                <%_ } _%>
                <%_ if (bcConfig && bcConfig.leftFilterFields) { _%>
                  <%_ bcConfig.leftFilterFields.filter(filterField => filterField).forEach(filterField => { _%>
                    <%_ if (((applicationTypeMonolith || applicationTypeMicroservice) && multiModule && moduleName && moduleName !== relationship.otherEntity.moduleName) ||
                            (applicationTypeMicroservice && !(relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName)))) { _%>
                if (criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(filterField) %>() != null) {
                    <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(filterField)%>(), <%= persistClass %>_.<%= relationship.relationshipName %><%= this._.upperFirst(filterField) %>));
                }
                    <%_ } else { _%>
                if (criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(filterField) %>() != null) {
                    <%= specificationInstance %> = CriteriaUtil.build(criteria.getUseOr(), <%= specificationInstance %>, buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %><%= this._.upperFirst(filterField) %>(),
                        root -> root.join(<%= persistClass %>_.<%= metamodelFieldName %>, JoinType.LEFT).get(<%= relationship.otherEntity.persistClass %>_.<%= filterField %>)));
                }
                    <%_ } _%>

                  <%_ }); _%>
                <%_ } _%>
                <%_ } }); /* forEach */ _%>
            }
        }
        return specification;
    }
<%_ } _%>
<%# add by begcode start %>
<%_ if (fieldsContainParentAndChildren) { _%>

    /**
    * Get all the <%= entityInstancePlural %> for parent is null.
    *<% if (!paginationNo) { %>
    * @param page the pagination information<% } %>
    * @return the list of entities
    */
    <%_ if (ormTool === 'hibernate') { _%>
    @Transactional
    <%_ } _%>
    public <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %>List<<%= instanceType %><% } %>> findAllTop(<%= criteria %> criteria, <% if (!paginationNo) { %><%- pageType %> page<% } %>) {
        LOG.debug("find by criteria : {}, page: {}", criteria, page);
        criteria.<%= relationshipParentIdName %>().setSpecified(false);
        final <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
    <%_ if (ormTool === 'mybatis') { _%>
        <%_ if (dtoMapstruct) { _%>
        return Binder
            .joinQueryPage(<%= specificationInstance %>, <%= persistClass %>.class, page)
            .convert(
                <%= entityInstance %> -> {
                    Binder.bindRelations(<%= entityInstance %>, new String[] {<%- [...ignoreRelationshipsOfTree].map(ignoreRel => `"${ignoreRel}"`).join(', ')%>});
                    return <%= mapper %>.toDto(<%= entityInstance %>);
                }
            );
        <%_ } else { _%>
        return Binder.joinQueryPage(<%= specificationInstance %>, <%= persistClass %>.class, page)
        <%_ } _%>
    <%_ } _%>
    <%_ if (ormTool === 'hibernate') { _%>
        <%_ if (paginationNo) { _%>
        return <%= entityInstance %>Repository.<% if (fieldsContainOwnerManyToMany) { %>findAllWithEagerRelationships<% } else { %>findAllByParentIsNull<% } %>()<% if (dtoMapstruct) { %>.stream()
            .map(<%= entityToDtoReference %>)
            .collect(Collectors.toCollection(LinkedList::new))<% } %>;
        <%_ } else { _%>
        return <%= repository %>.findAll(specification, page)<% if (dtoMapstruct) { %>.map(<%= entityToDtoReference %>)<% } %>;
        <%_ } _%>
    <%_ } _%>

    }

    /**
    * Get all the <%= entityInstancePlural %> for parent is parentId.
    *<% if (!paginationNo) { %>
    * @param parentId the Id of parent<% } %>
    * @return the list of entities
    */
    <%_ if (ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
    public <%= reactive ? 'Flux' : 'List'%><<%= instanceType %>> findChildrenByParentId(<%= primaryKey.type%> parentId) {
        LOG.debug("Request to get all <%= entityClassPlural %> for parent is parentId");
            <%_ if (ormTool === 'hibernate') { _%>
                <%_ if (dtoMapstruct) { _%>
        return <%= entityListToDto %>(<%= entityInstance %>Repository.findAllByParentId(parentId));
                <%_ } else { _%>
        return <%= entityInstance %>Repository.findAllByParentId(parentId);
                <%_ } _%>
            <%_ } else { _%>
        return <%= entityInstance %>Repository.selectList(new LambdaUpdateWrapper<<%= entityClass %>>().eq(<%= entityClass %>::getParentId, parentId))<% if (!dtoMapstruct) { %>;<% } else { %>
            .stream().map(<%= entityInstance %> -> {
            Binder.bindRelations(<%= entityInstance %>, new String[]{<%- [...ignoreRelationshipsOfTree].map(ignoreRel => `"${ignoreRel}"`).join(', ')%>});
                return <%= entityInstance %>Mapper.toDto(<%= entityInstance %>);
            }).collect(Collectors.toList());
            <%_ } _%>
        <% } %>
    }
<%_ } _%>

    public <T> List<T> getFieldByCriteria(Class<T> clazz,String fieldName, Boolean distinct, <%= persistClass %>Criteria criteria) {
<%_ if (ormTool === 'hibernate') { _%>
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> q = cb.createQuery(clazz);
        Root<<%= persistClass%>> root = q.from(<%= persistClass%>.class);
        Selection<T> selection = root.get(fieldName);
        q.distinct(distinct);
        q.select(selection);
        Predicate criteriaPredicate = createSpecification(criteria).toPredicate(root, q, cb);
        q.where(criteriaPredicate);
        return em.createQuery(q).getResultList();
<%_ } else { _%>
        return <%= repository %>.selectObjs(createQueryWrapperNoJoin(criteria).select(fieldName));
<%_ } _%>
    }

    public long countByFieldNameAndCriteria(String fieldName, Boolean distinct, <%= persistClass %>Criteria criteria) {
<%_ if ( ormTool === 'hibernate') { _%>
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Long> q = cb.createQuery(Long.class);
        Root<<%= persistClass%>> root = q.from(<%= persistClass%>.class);
        Selection<Long> selection;
        if (distinct != null && distinct) {
            selection = cb.countDistinct(root.get(fieldName)).alias("result");
        } else {
            selection = cb.countDistinct(root.get(fieldName)).alias("result");
        }
        q.select(selection);
        Predicate criteriaPredicate = createSpecification(criteria).toPredicate(root, q, cb);
        q.where(criteriaPredicate);
        return em.createQuery(q).getSingleResult();
<%_ } else { _%>
        return <%= repository %>.selectCount(createQueryWrapperNoJoin(criteria));
<%_ } _%>
    }
<%_ if (ormTool === 'hibernate') { _%>
    @Transactional
    public boolean updateBySpecifield(String fieldName, Object value, <%= criteria %> criteria) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaUpdate<<%= persistClass %>> q = cb.createCriteriaUpdate(<%= persistClass %>.class);
        CriteriaQuery<<%= persistClass %>> sq = cb.createQuery(<%= persistClass %>.class);
        Root<<%= persistClass %>> root = q.from(<%= persistClass %>.class);
        q.set(root.get(fieldName), value)
            .where(createSpecification(criteria).toPredicate(root,sq,cb));
        int result = em.createQuery(q).executeUpdate();
        em.flush();
        return result > 0;
    }

    <%_ if (useCommonTable) { _%>
    /**
     * 直接转换为dto。maytoone的，直接查询结果。one-to-many和many-to-many后续加载
     * @param entityName 模型名称
     * @param criteria 条件表达式
     * @param predicate 条件
     * @param pageable 分页
     * @return Page<<%= instanceType %>>
     */
    @Transactional(readOnly = true)
    public <%= pageName%><<%= instanceType %>> selectByCustomEntity(String entityName, <%= criteria %> criteria, Predicate predicate, <%= specificationType%> <%= specificationInstance%>, <%- pageType%> pageable) {
        List<<%= persistClass %>> dataList = new ArrayList<>();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tuple> q = cb.createTupleQuery();
        Root<<%= persistClass %>> root = q.from(<%= persistClass %>.class);
        if (StringUtils.isEmpty(entityName)) {
            entityName = "<%= persistClass %>";
        }
        Optional<CommonTableDTO> oneByEntityName = commonTableService.findOneByEntityName(entityName);
        List<String> fields = new ArrayList<>();
        List<CommonTableRelationshipDTO> toManyRelationships = new ArrayList<>();
        List<CommonTableRelationshipDTO> manyToOneRelationships = new ArrayList<>();
        List<Selection<?>> s = new ArrayList<>();
        if (oneByEntityName.isPresent()) {
            List<CommonTableFieldDTO> tableFields = oneByEntityName.get().getCommonTableFields().stream()
                .filter(commonTableField -> !commonTableField.getHideInList()).collect(Collectors.toList());
            tableFields.forEach(commonTableField -> fields.add(commonTableField.getEntityFieldName()));
            List<CommonTableRelationshipDTO> tableRelationships = oneByEntityName.get().getRelationships().stream()
                .filter(commonTableRelationship -> !commonTableRelationship.getHideInList()).collect(Collectors.toList());
            tableRelationships.forEach(commonTableRelationship -> {
                if (commonTableRelationship.getRelationshipType().equals(RelationshipType.ONE_TO_MANY) || commonTableRelationship.getRelationshipType().equals(RelationshipType.MANY_TO_MANY)) {
                    toManyRelationships.add(commonTableRelationship);
                } else {
                    try {
                        String clazzName = <%= persistClass %>.class.getDeclaredField(commonTableRelationship.getRelationshipName()).getType().getName();
                        manyToOneRelationships.add(commonTableRelationship);
                        root.join(commonTableRelationship.getRelationshipName(),JoinType.LEFT);
                        String idFieldName = JpaUtil.getPkColumn(clazzName);
                        String alaisId = commonTableRelationship.getRelationshipName() + "." + idFieldName;
                        s.add(root.get(commonTableRelationship.getRelationshipName()).get(idFieldName)
                            .alias(alaisId));
                        String relationPredicateAlias = commonTableRelationship.getRelationshipName() + "." + commonTableRelationship.getOtherEntityField();
                        if (s.stream().noneMatch(predicateRelation -> predicateRelation.getAlias().equals(relationPredicateAlias))) {
                            s.add(root.get(commonTableRelationship.getRelationshipName()).get(commonTableRelationship.getOtherEntityField())
                                .alias(relationPredicateAlias));
                        }
                    } catch (NoSuchFieldException e) {
                        LOG.error(e.getMessage());
                    }
                }
            });
        }
        s.addAll(fields.stream().map(fieldName -> root.get(fieldName).alias(fieldName)).collect(Collectors.toList()));
        q.multiselect(s);
        Predicate criteriaPredicate = createSpecification(criteria).toPredicate(root, q, cb);
        Predicate specificationPredicate = specification == null ? null : specification.toPredicate(root, q, cb);
        if (criteriaPredicate != null) {
            q.where(criteriaPredicate);
        } else if (predicate != null) {
            q.where(predicate);
        } else if (specificationPredicate != null) {
            q.where(specificationPredicate);
        }
        q.distinct(true);
        long totalItems;
        if (specificationPredicate != null) {
            totalItems = countBySpecification(specification);
        } else {
            totalItems = countByCriteria(criteria);
        }
        if (totalItems > 0) {
            if (pageable != null) {
                List<Order> orders = new ArrayList<>();
                pageable.getSort().forEach(
                    order -> orders.add(
                        order.isAscending() ?
                            cb.asc(root.get(order.getProperty())) :
                            cb.desc(root.get(order.getProperty()))));
                q.orderBy(orders);
            }
            TypedQuery<Tuple> query = em.createQuery(q);
            if (pageable != null) {
                pageable.getSort().toList();
                query.setFirstResult(pageable.getPageNumber()*pageable.getPageSize());
                query.setMaxResults(pageable.getPageSize());
            }
            List<Tuple> list = query.getResultList();
            for (Tuple tu : list
            ) {
                Map<String, Object> itemmap = new HashMap<>();
                for (TupleElement<?> element : tu.getElements()) {
                    itemmap.put(element.getAlias(), tu.get(element.getAlias()));
                }
                <%= persistClass %> <%= persistInstance%> = BeanUtil.mapToBean(itemmap, <%= persistClass %>.class, true);
                // 组装manytoone的内容
                manyToOneRelationships.forEach(relationship -> {
                    try {
                        String clazzName = <%= persistClass %>.class.getDeclaredField(relationship.getRelationshipName()).getType().getName();
                        String idFieldName = JpaUtil.getPkColumn(clazzName);
                        String alaisId = relationship.getRelationshipName() + "." + idFieldName;
                        String alaisField = relationship.getRelationshipName() + "." + relationship.getOtherEntityField();
                        Object relationObject = ReflectUtil.newInstance(clazzName);
                        if (itemmap.get(alaisId) != null) {
                            BeanUtil.setFieldValue(relationObject, idFieldName, itemmap.get(alaisId));
                            if (!alaisField.equals(alaisId)) {
                                BeanUtil.setFieldValue(relationObject, relationship.getOtherEntityField(), itemmap.get(alaisField));
                            }
                            BeanUtil.setFieldValue(<%= persistInstance%>,relationship.getRelationshipName(),relationObject);
                        }
                    } catch (NoSuchFieldException e) {
                        LOG.error(e.getMessage());
                    }
                });
                // 组装manytomany等的内容
                toManyRelationships.stream()
                    .filter(relationship -> ObjectUtils.isNotEmpty(FieldUtils.getField(<%= persistClass %>.class, relationship.getRelationshipName())))
                    .forEach(relationshipTemp -> {
                        CriteriaQuery<Tuple> subQuery = cb.createTupleQuery();
                        Class<?> clazz = ((PluralAttributePath<?>)root.get(relationshipTemp.getRelationshipName())).getAttribute().getElementType().getJavaType();
                        Root<?> manyRoot = subQuery.from(clazz);
                        if (clazz.getSimpleName().equals("<%= persistClass %>")) {
                            BeanUtil.setFieldValue(
                                <%= persistInstance%>, relationshipTemp.getRelationshipName(),
                                this.selectByCustomEntity(
                                    "<%= entityClass%>",
                                    null,
                                    cb.equal(manyRoot.get(relationshipTemp.getOtherEntityRelationshipName()).get("id"), itemmap.get("id")),  null, null));
                        } else {
                            Selection<Object> idAlias = manyRoot.get("id").alias("id");
                            if (relationshipTemp.getOtherEntityField() != null) {
                                subQuery.multiselect(idAlias, manyRoot.get(relationshipTemp.getOtherEntityField()).alias(relationshipTemp.getOtherEntityField()));
                                subQuery.where(cb.equal(manyRoot.get(relationshipTemp.getOtherEntityRelationshipName()).get("id"), itemmap.get("id")));
                                Set<Object> subdataList = new LinkedHashSet<>();
                                List<Tuple> sublist = em.createQuery(subQuery).getResultList();
                                for (Tuple stu : sublist) {
                                    Map<String, Object> subitemmap = new HashMap<>();
                                    for (TupleElement<?> element : stu.getElements()) {
                                        subitemmap.put(element.getAlias(), stu.get(element.getAlias()));
                                    }
                                    subdataList.add(BeanUtil.mapToBean(subitemmap, clazz, true));
                                }
                                BeanUtil.setFieldValue(<%= persistInstance%>, relationshipTemp.getRelationshipName(),subdataList);
                            } else {
                                // todo 暂时不予处理getOtherEntityField为null的情况。
                                LOG.error("<%= persistClass %>." + relationshipTemp.getRelationshipName() + "otherEntityField为空。");
                            }
                        }
                    });
                dataList.add(<%=persistInstance%>);
            }
        }
        return new PageImpl<>(<%= entityListToDto %>(dataList), pageable == null ? Pageable.unpaged() : pageable, totalItems);
    }
    <%_ } _%>

    /**
     * Return a {@link <%= instanceType %>} which matches the criteria from the database.
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching entity.
     */
    <%_ if (databaseTypeSql) { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
    public Optional<<%= instanceType %>> getOneByCriteria(<%= criteria %> criteria) {
        LOG.debug("find by criteria : {}", criteria);
        final <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
        <%_ if (ormTool === 'hibernate') { _%>
        return <%= repository %>.findOne(specification).map(<%= entityToDtoReference %>);
        <%_} else { _%>
        return Optional.of(<%= mapper %>.toDto(<%= repository %>.selectOne(<%= specificationInstance %>)));
        <%_ } _%>

    }

    /**
     * Return the number of matching entities in the database.
     * @param <%= specificationInstance %> The object which holds all the filters, which the entities should match.
     * @return the number of matching entities.
     */
    <%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
    public long countBy<%= specificationType %>(<%= specificationType%><<%= persistClass %>> <%= specificationInstance %>) {
        LOG.debug("count by <%= specificationInstance %> : {}", <%= specificationInstance %>);
        return <%= repository %>.<%= ormTool === 'hibernate' ? 'count' : 'selectCount'%>(<%= specificationInstance %>);
    }
<%_ } _%>
<%_ if (ormTool === 'mybatis') { _%>

    /**
     * Function to convert {@link <%= criteria %>} to a {@link <%= specificationType %>}
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching {@link <%= specificationType %>} of the entity.
     */
    public <%= specificationType %><<%= persistClass %>> create<%= specificationType %>(<%= criteria %> criteria) {
        if (StringUtils.isNotEmpty(criteria.getJhiCommonSearchKeywords())) {
            String keywords = criteria.getJhiCommonSearchKeywords();
            criteria.setJhiCommonSearchKeywords(null);
            <%= criteria %> keywordsCriteria = new <%= criteria %>();
            keywordsCriteria.setUseOr(true);
            if (StringUtils.isNumeric(keywords)) {
                <%_ filterFields.filter(field => ['Integer', 'Long', 'Float', 'Double', 'BigDecimal', 'Duration'].includes(field.fieldType))
                    .forEach(field => { _%>
                keywordsCriteria.<%= field.fieldName %>().setEquals(<% if (field.fieldType=== 'BigDecimal') { %>new BigDecimal<% } else { %><%= field.fieldType%>.valueOf<% } %>(keywords));
                <%_ }); _%>
            }
            <%_ filterFields.filter(field => ['String'].includes(field.fieldType)).forEach((field) => { _%>
            keywordsCriteria.<%= field.fieldName %>().setContains(keywords);
            <%_ }); _%>
            <%= criteria %> tempCriteria = criteria;
            while (tempCriteria.getAnd() != null) {
                tempCriteria = tempCriteria.getAnd();
            }
            tempCriteria.setAnd(keywordsCriteria);
        }
        List<String> fields = CriteriaUtil.getNonNullBindQueryFields(criteria);
        QueryWrapper<<%= persistClass %>> queryWrapper = new DynamicJoinQueryWrapper<>(<%= criteria %>.class, fields);
        return create<%= specificationType %>(queryWrapper, criteria.getUseOr(), criteria, <%= persistClass %>.class);
    }

    /**
     * Function to convert {@link <%= criteria %>} to a {@link <%= specificationType %>}
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching {@link <%= specificationType %>} of the entity.
     */
    public <%= specificationType %><<%= persistClass %>> create<%= specificationType %>NoJoin(<%= criteria %> criteria) {
        QueryWrapper<<%= persistClass %>> queryWrapper = new QueryWrapper<>();
        return create<%= specificationType %>NoJoin(queryWrapper, criteria.getUseOr(), criteria, <%= persistClass %>.class);
    }
    <%_ if (useCommonTable) { _%>

    /**
     * 直接转换为dto。maytoone的，直接查询结果。one-to-many和many-to-many后续加载
     * @param entityName 模型名称
     * @param criteria 条件表达式
     * @param pageable 分页
     * @return Page<<%= instanceType %>>
     */
    public synchronized Page<<%= instanceType %>> selectByCustomEntity(String entityName, <%= criteria %> criteria, <%= specificationType%> <%= specificationInstance%>, Page<<%= persistClass %>> pageable) {
        if (StringUtils.isEmpty(entityName)) {
            entityName = "<%= persistClass %>";
        }
        queryWrapper = createQueryWrapper(criteria);
        Optional<CommonTableDTO> commonTableDTO = commonTableService.findOneByEntityName(entityName);
        List<String> dynamicFields = new ArrayList<>();
        List<String> dynamicRelationships = new ArrayList<>();
        commonTableDTO.ifPresent(commonTable ->  {
            commonTable.getCommonTableFields().stream()
                .filter(commonTableField -> !commonTableField.getHideInList())
                .forEach(commonTableField -> dynamicFields.add(commonTableField.getEntityFieldName()));
            commonTable.getRelationships().stream()
                .filter(commonTableRelationship -> !commonTableRelationship.getHideInList())
                .forEach(commonTableRelationship -> dynamicRelationships.add(commonTableRelationship.getRelationshipName()));
        });
        // DynamicJoinQueryWrapper<<%= persistClass %>, <%= persistClass %>> dynamicJoinQueryWrapper = new DynamicJoinQueryWrapper<>(<%= persistClass %>.class, dynamicRelationships);
        String[] fields = new String[dynamicFields.size()];
        dynamicFields.toArray(fields);
        queryWrapper.select(fields);
        List<String> orders = pageable.orders().stream()
            .map(orderItem -> orderItem.getColumn() + ':' + (orderItem.isAsc() ? "ASC" : "DESC"))
            .collect(Collectors.toList());
        Pagination pagination = new Pagination().setOrderBy(String.join(",", orders));
        pagination.setPageSize((int) pageable.getSize());
        pagination.setPageIndex((int) pageable.getCurrent());
        List<<%= instanceType %>> result =  ((DynamicJoinQueryWrapper<<%= persistClass %>, <%= persistClass %>>)queryWrapper).queryList(<%= persistClass %>.class, pagination).stream()
            .peek(Binder::bindRelations)
            .map(<%= entityToDtoReference %>).collect(Collectors.toList());
        return new Page<<%= instanceType %>>(pagination.getPageIndex(), pagination.getPageSize(), pagination.getTotalCount()).setRecords(result);
    }
    <%_ } _%>
<%_ } _%>
    /**
     * Return a {@link <%= pageName%>} of {@link <%= instanceType %>} which matches the criteria from the database.
     * @param <%= specificationInstance%> The object which holds all the filters, which the entities should match.
     * @param page The page, which should be returned.
     * @return the matching entities.
     */
    <%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
    public <%= pageName%><<%= instanceType %>> findBy<%= specificationType %>(<%= specificationType%><<%= persistClass %>> <%= specificationInstance%>, <%- pageType%> page) {
        LOG.debug("find by criteria : {}, page: {}", <%= specificationInstance %>, page);
        return <%= repository %>.<%= ormTool !== 'mybatis' ? `findAll(${specificationInstance}, page)` : `selectPage(page, ${specificationInstance})`%>
            .<%= ormTool !== 'mybatis' ? 'map' : 'convert'%>(<%= entityToDtoReference %>);
    }

    public List<Map<String, Object>> statsByAggregateCriteria(<%= persistClass %>Criteria criteria) {
        <%_ if (ormTool === 'mybatis') { _%>
        <%= specificationType %><<%= persistClass %>> <%= specificationInstance %> = create<%= specificationType %>(criteria);
        List<String> selectFields = new ArrayList<>();
        List<String> groupByFields = new ArrayList<>();
        Map<String, Map<String, Object>> fieldNameMap = CriteriaUtil.getNonIgnoredAndNonNullFields(criteria);
        fieldNameMap
            .forEach((key, value) -> {
                // 获得value 对象BindQuery 注解的column属性值
                Filter<?> filter = (Filter<?>) value.get("value");
                BindQuery bindQuery = (BindQuery) value.get("bindQuery");
                String column = bindQuery.column();
                if (column.startsWith("self.")) {
                    getAggregateAndGroupBy(filter, column, "", selectFields, groupByFields);
                } else {
                    if (queryWrapper instanceof DynamicJoinQueryWrapper) {
                        DynamicJoinQueryWrapper<<%= persistClass %>Criteria, <%= persistClass %>> dynamicQuery = (DynamicJoinQueryWrapper<<%= persistClass %>Criteria, <%= persistClass %>>) queryWrapper;
                        dynamicQuery.getAnnoJoiners().stream()
                            .filter(annoJoiner -> annoJoiner.getColumnName().equals(column) && annoJoiner.getFieldName().equals(key))
                            .findFirst()
                            .ifPresent(annoJoiner -> {
                                String alias = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, annoJoiner.getFieldName());
                                getAggregateAndGroupBy(filter, annoJoiner.getAlias() + "." + column, alias, selectFields, groupByFields);
                            });
                    }
                }
            });
        <%_ } else { _%>
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tuple> q = cb.createQuery(Tuple.class);
        Root<<%= persistClass %>> root = q.from(<%= persistClass %>.class);
        List<Selection<?>> selectFields = new ArrayList<>();
        List<Expression<?>> groupByFields = new ArrayList<>();
        Map<String, Filter<?>> fieldNameMap = new HashMap<>();
        <%_
        filterFields.forEach(field => {
          if (field.filterableField) {
        _%>
        fieldNameMap.put("self.<%= field.columnName %>", criteria.get<%= field.fieldInJavaBeanMethod %>());
        <%_
        }});
        _%>
        <%_
        filterRelationships.filter(filterRelation => filterRelation.relationshipManyToOne && filterRelation.ownerSide)
        .forEach(filterRelation => { _%>
        fieldNameMap.put("self.<%= filterRelation.columnName + '_' + filterRelation.otherEntity.primaryKey.fields[0].columnName %>", criteria.get<%= filterRelation.propertyJavaFilterJavaBeanName %>());
        <%_ }); _%>
        fieldNameMap
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() != null)
            .forEach(entry -> getAggregateAndGroupBy(entry.getValue(), entry.getKey(), selectFields, groupByFields<% if (ormTool === 'hibernate') { %>, cb, root<% } %>));
        <%_ } _%>
        if (CollectionUtils.isNotEmpty(selectFields)) {
            <%_ if (ormTool === 'mybatis') { _%>
            <%= specificationInstance %>.select(selectFields.toArray(new String[0])).groupBy(CollectionUtils.isNotEmpty(groupByFields), groupByFields);
            return Binder.joinQueryMapsPage(queryWrapper, <%= persistClass %>.class, null).getRecords();
            <%_ } else { _%>
            q.multiselect(selectFields);
            Predicate criteriaPredicate = createSpecification(criteria).toPredicate(root, q, cb);
            q.where(criteriaPredicate);
            q.groupBy(groupByFields);
            return em.createQuery(q).getResultList().stream().map(JpaUtil::toMap).collect(Collectors.toList());
            <%_ } _%>
        }
        return Collections.emptyList();
    }
<%_ if (addCustomMethod.indexOf('queryService') !== -1) { _%>
<%- include(`../../_entityCustom_/${entityClass}.queryService.ejs`, {position: 'method'}); -%>
<%_ } _%>
<%_ Object.keys(addMethodWithAnnotations).forEach(addKey => {
    const params = addMethodWithAnnotations[addKey].replace(' ', '');
    const paramFieldNames = params.split('-');
    const paramFields = {};
    paramFieldNames.forEach(fieldName => {
        fields.find(field => {
            if (fieldName === field.fieldName) {
                paramFields[fieldName] = field;
            }
        })
    });
_%>
    <%_ if (addKey.startsWith('findAllBy') || addKey.startsWith('findOneBy')) { _%>
    public <% if (addKey.startsWith('findAllBy')) { %>List<<%= instanceType %>><% } else { %><%= instanceType %><% } %> <%= addKey %>(<% Object.keys(paramFields).forEach((fieldName, index) => {%><%= paramFields[fieldName].fieldType%> <%= fieldName %><%= index === (Object.keys(paramFields).length - 1) ? '' : ', '%><% });%>) {
       <%_ if (ormTool === 'mybatis') { _%>
        return <%= entityListToDto %>(<%= repository %>.<%= addKey.startsWith('findAllBy') ? 'selectList' : 'selectOne'%>(
            new LambdaQueryWrapper<<%= entityClass %>>()
                <%_ Object.keys(paramFields).forEach((fieldName, index) => { _%>
                .eq(<%= entityClass %>::get<%= paramFields[fieldName].fieldNameCapitalized %>, <%= fieldName %>)
                <%_ });_%>
            ));
       <%_ } else { %>
       <%_ } _%>
    }
    <%_ } _%>
<%_ }); _%>
<%# add by begcode end %>
}
