<%#
 Copyright 2013-2023 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<% } %>.base;

<%_
// add by begcode start
const sortFields = fields.filter(field => field.options && field.options.sortField);
const alainServiceConfig = {}; // add by wangxin
const relationshipsForCache = [];
const skipRelationships = this._reflexRelationship(relationships, entityClass);
const beans = [];
let extensibleDataClass;
let extensibleDataInstance;
for (idx in relationships) {
    if (relationships[idx].relationshipType === 'many-to-one' && relationships[idx].otherEntityRelationshipName) {
        relationshipsForCache.push(relationships[idx]);
    }
    if (relationships[idx].relationshipType === 'one-to-one' && !relationships[idx].ownerSide && relationships[idx].bcConfig && relationships[idx].bcConfig.jhiExt) {
        extensibleDataClass = relationships[idx].otherEntityNameCapitalized;
        extensibleDataInstance = relationships[idx].otherEntityName;
    }
}
const ignoreRelationshipsOfTree = [];
const dtoRelationships = dtoReferences.filter(reference => reference.relationship);
const dtoChildrenRelationshipsName = dtoRelationships
        .filter(reference => reference.leafOfTree)
        .map(reference => reference.name);
for (relationship of relationships) {
    if (dtoChildrenRelationshipsName && !dtoChildrenRelationshipsName.includes(relationship.relationshipName)) {
        ignoreRelationshipsOfTree.push(relationship.relationshipName);
    }
}
const pageOrFlux = reactive ? 'Flux' : (ormTool !== 'mybatis' ? 'Page' : 'IPage');
const searchPageOrFlux = reactive ? 'Flux' : (ormTool !== 'mybatis' ? 'Page' : 'org.springframework.data.domain.Page');
const pageType = ormTool !== 'mybatis' ? 'Pageable' : `Page<${entityClass}>`;
// add by begcode end
const serviceClassName = serviceImpl ? entityClass + 'BaseServiceImpl' : entityClass + 'BaseService';
const instanceType = restClass;
const instanceName = restInstance;
const optionalOrMono = (reactive) ? 'Mono' : 'Optional';
const listOrFlux = (reactive) ? 'Flux' : 'List';
const mapper = entityInstance  + 'Mapper';
const dtoToEntity = mapper + '.'+ 'toEntity';
const entityToDto = 'toDto';
const entityToDtoReference = mapper + '::'+ 'toDto';
const repository = entityInstance  + 'Repository';
const searchRepository = entityInstance  + 'SearchRepository';

_%>
<%_ if (serviceImpl || multiModule) { _%>
import <%= entityAbsolutePackage %>.service.base.<%= entityClass %>BaseService;
<%_ } _%>
import <%= entityAbsolutePackage %>.domain.<%= persistClass %>;
<%_ if (jpaMetamodelFiltering && reactive) {  _%>
import <%= entityAbsolutePackage %>.domain.criteria.<%= entityClass %>Criteria;
<%_ }  _%>
import <%= entityAbsolutePackage %>.repository.<%= entityClass %>Repository;
<%_ if (isUsingMapsId === true) { _%>
import <%= entityAbsolutePackage %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= entityAbsolutePackage %>.repository.search.<%= entityClass %>SearchRepository;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>;
import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper;
<%_ } _%>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

<%_ if (!paginationNo || implementsEagerLoadApis) { _%>
  <%_ if (!reactive && ormTool === 'hibernate') { _%>
import org.springframework.data.domain.Page;
  <%_ } _%>
  <%_ if (!reactive && (ormTool === 'hibernate' || searchEngineElasticsearch)) { _%>
import org.springframework.data.domain.Pageable;
  <%_ } _%>
<%_ } _%>
<%_ if (false) { _%>
import org.springframework.stereotype.Service;
<%_ } _%>
<%_ if (databaseTypeSql) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (reactive) { _%>
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } _%>

import java.util.*;
import org.apache.commons.collections4.CollectionUtils;
<%_ if (ormTool === 'mybatis' && sortFields && sortFields.length > 0) { %>
import org.apache.commons.lang3.ObjectUtils;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import <%= packageName %>.domain.enumeration.SortValueOperateType;
<%_ } _%>
<%_ if (fieldsContainNoOwnerOneToOne || (paginationNo && ((searchEngine) || dtoMapstruct))) { _%>
import java.util.stream.Collectors;
<%_ } _%>
<%_ if (fieldsContainNoOwnerOneToOne || (paginationNo && searchEngineElasticsearch)) { _%>
import java.util.stream.StreamSupport;
<%_ } _%>
<%# add by begcode start %>
<%_ const { showInOneConfig, n2nConfig } = (bcEntityData || { formFieldLines: [], showInOneRelationships: {}, showInOneConfig: {} }); _%>
<%_ if (relationshipsForCache && relationshipsForCache.length > 0 && !reactive || (showInOneConfig && Object.keys(showInOneConfig).length > 0) || (n2nConfig && Object.keys(n2nConfig).length > 0)) { _%>
import java.util.Arrays;
<%_ } _%>
<%_ const importedOther = [persistClass]; _%>
<%_ if (showInOneConfig && Object.keys(showInOneConfig).length > 0) { _%>
    <%_ if (Object.keys(showInOneConfig).length === 1)  {
        const showInOneConfigRelationship = showInOneConfig[Object.keys(showInOneConfig)[0]].relationship;
        let relationshipNameCapitalized = showInOneConfigRelationship.otherRelationship.relationshipNameCapitalized;
        if (showInOneConfigRelationship.otherRelationship.relationshipRightSide && showInOneConfigRelationship.otherRelationship.bcConfig.leftRelateByIdEntity) {
            relationshipNameCapitalized = 'OwnerEntity';
        }
        importedOther.push(showInOneConfigRelationship.otherEntity.persistClass);
    _%>
import <%= showInOneConfigRelationship.otherEntity.entityAbsolutePackage %>.domain.<%= showInOneConfigRelationship.otherEntity.persistClass %>;
    <%_ } _%>
<%_ } _%>
<%_ relationships.filter(relationship => !relationship.ownerSide && (relationship.relationshipOneToMany || relationship.relationshipManyToMany)).forEach(relationship => { _%>
  <%_ if (!importedOther.includes(relationship.otherEntity.persistClass)) { _%>
import <%= relationship.otherEntity.entityAbsolutePackage %>.domain.<%= relationship.otherEntity.persistClass %>;
  <%_ } _%>
<%_ }); _%>
<%_ if (ormTool === 'hibernate' || ormTool === 'mybatis' && extendData) { _%>
import java.util.stream.Collectors;
<%_ } _%>
<%_ if (ormTool === 'hibernate') { _%>
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
<%_ } _%>
<%_ if (!cacheProviderNo) { _%>
  <%_ if (relationshipsForCache.length > 0 && !reactive) { _%>
import org.springframework.cache.Cache;
  <%_ } _%>
import org.springframework.cache.CacheManager;
<%_ } _%>
import cn.hutool.core.bean.BeanUtil;
<%_ if (extendData) { _%>
import <%= packageName %>.service.CommonExtDataService;
<%_ } _%>
<%_ if (ormTool === 'mybatis') { _%>
import com.diboot.core.binding.Binder;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  <%_ if (fieldsContainParentAndChildren) { _%>
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  <%_ } _%>
import com.google.common.base.CaseFormat;
<%_ } _%>
<%_ if (addCustomMethod.indexOf('service') !== -1) { _%>
<%- include(`../../../_entityCustom_/${entityClass}.service.ejs`, {position: 'import'}); -%>
<%_ } _%>
<%# add by begcode end %>

// jhipster-needle-add-import - JHipster will add getters and setters here, do not remove

/**
 * Service Implementation for managing {@link <%= entityAbsoluteClass %>}.
 */
<%_ if (false) { _%><%# 移动到实现类中了 _%>
@Service<% if (databaseTypeSql && ormTool === 'hibernate') { %>
@Transactional<% } %>
<%_ } _%>
<%_ if (ormTool === 'hibernate') { _%>
public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= entityClass %>Service<% } %><% if (addCustomMethod.indexOf('service') !== -1) { %><%- include(`../../../_entityCustom_/${entityClass}.service.ejs`, {position: 'classImplements'}); -%><% } %> {
<%_ } else { _%>
public class <%= serviceClassName %><R extends <%= entityClass%>Repository, E extends <%= entityClass%>> extends BaseServiceImpl<<%= entityClass %>Repository, <%= entityClass %>><% if (serviceImpl || multiModule) { %> implements <%= entityClass %>BaseService<% } %><% if (addCustomMethod.indexOf('service') !== -1) { %><%- include(`../../../_entityCustom_/${entityClass}.service.ejs`, {position: 'classImplements'}); -%><% } %> {
<%_ } _%>

    private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class);
<%_ if (relationshipsForCache && relationshipsForCache.length > 0 && !reactive) { _%>

    private final List<String> relationCacheNames =
        Arrays.asList(
        <%_ const tempRelationships = relationships.filter(relationship => !relationship.bcConfig || !relationship.bcConfig.unidirectionSkip)
            for (idx in tempRelationships) {
            const bcConfig = tempRelationships[idx].bcConfig || {};
            if (!bcConfig.unidirectionSkip) {
        _%>
            <%_
            if (!(((applicationTypeMonolith || applicationTypeMicroservice) && multiModule && moduleName && moduleName !== tempRelationships[idx].otherEntity.moduleName) ||
                    (applicationTypeMicroservice && !(tempRelationships[idx].otherEntity.applications.includes('*') || tempRelationships[idx].otherEntity.applications.includes(baseName))))
            ) {
            _%>
        <%= tempRelationships[idx].otherEntity.entityAbsolutePackage %>.domain.<%= tempRelationships[idx].otherEntityNameCapitalized%>.class.getName() + ".<%= tempRelationships[idx].otherEntityRelationshipName%>"<%= idx < tempRelationships.length - 1 ? ',' : ''%>
            <%_ } _%>
        <%_ } } _%>
        );
<%_ } _%>
    private final List<String> relationNames = Arrays.asList(
        <%_ for (idx in relationships) { _%>
        "<%= relationships[idx].relationshipName%>"<%= idx < relationships.length - 1 ? ',' : ''%>
        <%_ } _%>
    );
    <% if (addCustomMethod.indexOf('service') !== -1) { %><%- include(`../../../_entityCustom_/${entityClass}.construct.ejs`, {viaService: false,isController: false, beans: beans});-%><% } %>
<%- include('../../_partials_entity_/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false, beans}); -%><%# modify by begcode %>

    <%_ if (!(replaceServiceMethod && replaceServiceMethod.indexOf('save') !== -1)) { _%>
<%_ if (!serviceImpl) { _%>
    /**
     * Save a <%= entityInstance %>.
     *
     * @param <%= instanceName %> the entity to save.
     * @return the persisted entity.
     */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
<%_ if (ormTool === 'mybatis') { _%>
    @Transactional
<%_ } _%>
    public <% if (reactive) { %>Mono<<% } %><% if (!dtoMapstruct && ormTool === 'mybatis') { %>boolean<% } else { %><%= instanceType %><% } %><% if (reactive) { %>><% } %> save(<%= instanceType %> <%= instanceName %>) {
        log.debug("Request to save <%= entityClass %> : {}", <%= instanceName %>);
<%- include('/_global_partials_entity_/save_template', {viaService: false, returnDirectly: true, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false, isPersisted: false, skipRelationships: skipRelationships}); -%>
    }
    <%_ } _%>

<%_ if (!serviceImpl) { _%>
    /**
     * Update a <%= entityInstance %>.
     *
     * @param <%= instanceName %> the entity to save.
     * @return the persisted entity.
    */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
<%_ if (ormTool === 'mybatis') { _%>
    @Transactional(rollbackFor = Exception.class)
<%_ } _%>
    public <% if (reactive) { %>Mono<<% } %><%= instanceType %><% if (reactive) { %>><% } %> update(<%= instanceType %> <%= instanceName %>) {
        log.debug("Request to update <%= entityClass %> : {}", <%= instanceName %>);
<%- include('/_global_partials_entity_/update_template', {updatableEntity, viaService: false, returnDirectly: true, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false, isPersisted: requiresPersistableImplementation}); -%>
    }

<%_ if (!serviceImpl) { _%>
    /**
     * Partially update a <%= entityInstance %>.
     *
     * @param <%= instanceName %> the entity to update partially.
     * @return the persisted entity.
     */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
<%_ if (ormTool === 'mybatis') { _%>
    @Transactional
<%_ } _%>
    public <% if (reactive) { %>Mono<% } else { %>Optional<% } %><<%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) {
        log.debug("Request to partially update <%= entityClass %> : {}", <%= instanceName %>);
<%- include('../../_partials_entity_/patch_template', {isService: true, viaService: false}); -%>
    }

<%_ if (!serviceImpl) { _%>
    /**
     * Get all the <%= entityInstancePlural %>.
     *
  <%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
  <%_ } _%>
     * @return the list of entities.
     */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
<%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
<%_ } _%>
    public <% if (paginationNo) { %><%= listOrFlux %><% } else { %><%= pageOrFlux %><% } %><<%= instanceType %>> findAll(<% if (!paginationNo) { %><%- pageType %> pageable<% } %>) {
        log.debug("Request to get all <%= entityClassPlural %>");
<%_ if (paginationNo) { _%>
        return <%= entityInstance %>Repository.findAll()<% if (dtoMapstruct) { %><% if (!reactive) { %>.stream()<% } %>
            .map(<%= entityToDtoReference %>)<% if (!reactive) { %>
            .collect(Collectors.toCollection(LinkedList::new))<% } } %>;
<%_ } else { _%>
    <%_ if (ormTool === 'hibernate') { _%>
        return <%= entityInstance %>Repository.findAll<% if (reactive) { %>By<% } %>(pageable)<% if (!dtoMapstruct) { %>;<% } else { %>
            .map(<%= entityToDtoReference %>);<% } %>
    <%_ } else { _%>
    return this.page(pageable)<% if (!dtoMapstruct) { %>;<% } else { %>.convert(<%= entityToDtoReference %>);<% } %>;
    <%_ } _%>
<%_ } _%>
    }

<%_ if (jpaMetamodelFiltering && reactive) {  _%>
    <%_ if (!serviceImpl) { _%>
    /**
    * Find <%= entityInstancePlural %> by Criteria.
    *
    <%_ if (!paginationNo) { _%>
    * @param pageable the pagination information.
    <%_ } _%>
    * @return the list of entities.
    */
    <%_ } _%>
    <%_ if (serviceImpl) { _%>
    @Override
    <%_ } _%>
    <%_ if (databaseTypeSql) { _%>
    @Transactional<% if (ormTool === 'hibernate') { %>(readOnly = true)<% } %>
    <%_ } _%>
    public <% if (paginationNo) { %><%= listOrFlux %><% } else { %><%= pageOrFlux %><% } %><<%= instanceType %>> findByCriteria(<%= entityClass %>Criteria criteria<% if (!paginationNo) { %>, <%- pageType%> pageable<% } %>) {
        log.debug("Request to get all <%= entityClassPlural %> by Criteria");
    <%_ if (paginationNo) { _%>
        return <%= entityInstance %>Repository.findByCriteria(criteria, null)<% if (dtoMapstruct) { %>.map(<%= entityToDtoReference  %>)<% } %>;
    <%_ } else { _%>
        return <%= entityInstance %>Repository.findByCriteria(criteria, pageable)<% if (dtoMapstruct) { %>.map(<%= entityToDtoReference  %>)<% } %>;
    <%_ } _%>
    }

    /**
    * Find the count of <%= entityInstancePlural %> by criteria.
    * @param criteria filtering criteria
    * @return the count of <%= entityInstancePlural %>
    */
    public Mono<Long> countByCriteria(<%= entityClass %>Criteria criteria) {
        log.debug("Request to get the count of all <%= entityClassPlural %> by Criteria");
        return <%= entityInstance %>Repository.countByCriteria(criteria);
    }
    <%_ }  _%>


<%_ if (implementsEagerLoadApis && ormTool === 'hibernate') { _%>

  <%_ if (!serviceImpl) { _%>
    /**
     * Get all the <%= entityInstancePlural %> with eager load of many-to-many relationships.
     *
     * @return the list of entities.
     */
  <%_ } _%>
    public <%= pageOrFlux %><<%= instanceType %>> findAllWithEagerRelationships(Pageable pageable) {
        return <%= entityInstance %>Repository.findAllWithEagerRelationships(pageable)<% if (!dtoMapstruct) { %>;<% } else { %>.map(<%= entityToDtoReference %>);<% } %>
    }
<%_ } _%>
<%- include('../../_partials_entity_/get_filtered_template'); -%>
<%_ if (reactive) { _%>
  <%_ if (!serviceImpl) { _%>
    /**
     * Returns the number of <%= entityInstancePlural %> available.
     * @return the number of entities in the database.
     *
     */
  <%_ } _%>
    public Mono<Long> countAll() {
        return <%= entityInstance %>Repository.count();
    }
  <%_ if (searchEngineElasticsearch) { _%>

    <%_ if (!serviceImpl) { _%>
    /**
     * Returns the number of <%= entityInstancePlural %> available in search repository.
     *
     */
    <%_ } _%>
    public Mono<Long> searchCount() {
        return <%= entityInstance %>SearchRepository.count();
    }
  <%_ } _%>

<%_ } _%>
<%_ if (!serviceImpl) { _%>
    /**
     * Get one <%= entityInstance %> by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
<%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
<%_ } _%>
    public <%= optionalOrMono %><<%= instanceType %>> findOne(<%= primaryKey.type %> id) {
        log.debug("Request to get <%= entityClass %> : {}", id);<%- include('../../_partials_entity_/get_template', {viaService: false, returnDirectly:true, implementsEagerLoadApis}); -%>
    }
<%_ if (softDelete && !skipSoftDelete) { _%>

  <%_ if (serviceImpl) { _%>
    @Override
  <%_ } _%>
  <%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
  <%_ } _%>
    public <%= optionalOrMono %><<%= instanceType %>> findOneInRecycleBin(<%= primaryKey.type %> id) {
        log.debug("Request to get <%= entityClass %> : {}", id);<%- include('../../_partials_entity_/get_recycle_bin_template', {viaService: false, returnDirectly:true, implementsEagerLoadApis}); -%>
    }

    public void restoreByIdsInRecycleBin(List<<%= primaryKey.type %>> ids) {
        lambdaUpdate().set(<%= entityClass %>::getDelFlag, false).set(<%= entityClass %>::getDeletedTime, null).in(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, ids).update();
    }
<%_ } _%>

<%_ if (!serviceImpl) { _%>
    /**
     * Delete the <%= entityInstance %> by id.
     *
     * @param id the id of the entity.
  <%_ if (reactive) { _%>
     * @return a Mono to signal the deletion
  <%_ } _%>
     */
<%_ } _%>
<%_ if (serviceImpl) { _%>
    @Override
<%_ } _%>
    @Transactional<% if (ormTool === 'mybatis') { %>(rollbackFor = Exception.class)<% } %>
    public <%- reactive ? 'Mono<Void>' : 'void' %> delete(<%= primaryKey.type %> id) {
        log.debug("Request to delete <%= entityClass %> : {}", id);
<%- include('../../_partials_entity_/delete_template', {viaService: false, fromResource: false}); -%>
    }
<%_ if (searchEngineAny) { _%>

  <%_ if (!serviceImpl) { _%>
    /**
     * Search for the <%= entityInstance %> corresponding to the query.
     *
     * @param query the query of the search.
    <%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
    <%_ } _%>
     * @return the list of entities.
     */
  <%_ } _%>
  <%_ if (serviceImpl) { _%>
    @Override
  <%_ } _%>
  <%_ if (databaseTypeSql) { _%>
    @Transactional<%_ if (ormTool === 'hibernate') { _%>(readOnly = true)<% } %>
  <%_ } _%>
    public <% if (!paginationNo) { %><% if (!reactive && ormTool === 'mybatis') { %>org.springframework.data.domain.Page<% } else { %><%= pageOrFlux %><% } %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> search(String query<% if (!paginationNo) { %>, Pageable pageable<% } %>) {
  <%_ if (paginationNo) { _%>
        log.debug("Request to search <%= entityClassPlural %> for query {}", query);<%- include('../../_partials_entity_/search_stream_template', {viaService: false, fromResource: false}); -%>
  <%_ } else { _%>
        log.debug("Request to search for a page of <%= entityClassPlural %> for query {}", query);
        return <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(query, pageable)<%_ if (!dtoMapstruct) { _%>;<% } else { %>
            .map(<%= entityToDtoReference %>);
        <%_ } _%>
  <%_ } _%>
    }
<%_ } _%>
<%# add by begcode start %>
    <%_ if (addCustomMethod.indexOf('service') !== -1) { _%>

    <%- include(`../../../_entityCustom_/${entityClass}.service.ejs`, { serviceImpl: true, position: 'method', skipRelationships: skipRelationships }); -%>
    <%_ } _%>
<%_ if (ormTool === 'hibernate' && databaseTypeSql) { _%>
        <%_ if (!reactive) { _%>

<%_ if (!serviceImpl) { _%>
    /**
     * Get one <%= entityInstance %> by example.
     *
     * @param example the example of the entity.
     * @return the entity.
     */
    <%_ } _%>
    <%_ if (serviceImpl) { _%>
    @Override
    <%_ } _%>
    public <%= optionalOrMono %><<%= instanceType %>> findOneByExample(Example<<%= entityClass %>> example) {
        log.debug("Request to get <%= entityClass %> by example");
        return <%= entityInstance %>Repository.findAll(example).stream().findFirst().map(<%= entityInstance %>Mapper::toDto);
    }

    <%_ if (!serviceImpl) { _%>
    /**
     * Get all the <%= entityInstancePlural %> by example.
     *
     * @param example the example of the entity.
     * @return the entities.
     */
    <%_ } _%>
    <%_ if (serviceImpl) { _%>
    @Override
    <%_ } _%>
    @Transactional(readOnly = true)
    public <%= pageOrFlux %><<%= instanceType %>> findAllByExample(Example<<%= entityClass %>> example, Pageable pageable) {
        log.debug("Request to get <%= entityClass %> by example");
        return <%= entityInstance %>Repository.findAll(example, pageable)
            .map(<%= entityInstance %>Mapper::toDto);
    }
        <%_ } _%>
    <%_ } _%>
<%# user 相关 %>
<%_ for (idx in relationships) { _%>
        <%_ if (relationships[idx].relationshipType === 'many-to-one' && relationships[idx].otherEntityName === 'user') { _%>
            <%_ if (databaseTypeSql) { _%>
                <%_ if (ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
                <%_ } _%>
    public List<<%= instanceType %>> findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser() {
        return <%= mapper%>.toDto(<%= entityInstance %>Repository.findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser());
    }
            <%_ } else if (databaseTypeMongodb) { _%>
    public List<<%= instanceType %>> findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser() {
        return <%= mapper%>.toDto(<%= entityInstance %>Repository.findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser(SecurityUtils.getCurrentUserId().get()));
    }
            <%_ } else { _%>
    public List<<%= instanceType %>> findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser() {
        return <%= mapper%>.toDto(<%= entityInstance %>Repository.findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser());
    }
            <%_ } _%>
        <%_ } _%>
        <%_ if (relationships[idx].relationshipType === 'one-to-one' && relationships[idx].otherEntityName === 'user' && databaseTypeSql) { _%>

        <%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>
    @Transactional(readOnly = true)
        <%_ } _%>
    public Optional<<%= instanceType %>> getBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser() {
        return <%= entityInstance %>Repository.getBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser().map(<%= mapper%>::toDto);
    }
        <%_ } _%>
<%_ } _%>

    <%_ if (!serviceImpl) { _%>
    /**
     * Update specified field by <%= entityInstance %>
     */
    <%_ } _%>
    <%_ if (serviceImpl) { _%>
    @Override
    <%_ } _%>
    <%_ if (ormTool === 'mybatis') { _%>
    @Transactional
    <%_ } _%>
    public void updateBatch(<%= instanceType %> change<%= instanceType %>, List<String> fieldNames, List<<%= primaryKey.type %>> ids) {
        <%_ if (ormTool === 'hibernate') { _%>
        <%= entityInstance %>Repository.findAllById(ids).stream()
            .peek(<%= persistInstance %> ->
                fieldNames.forEach(fieldName ->
                    BeanUtil.setFieldValue(<%= persistInstance %>, fieldName,
                        BeanUtil.getFieldValue(change<%= instanceType %>, fieldName))))
            .forEach(<%= entityInstance %>Repository::save);
        <%_ } else { _%>
        List<String> relationshipNames = CollectionUtils.intersection(fieldNames, relationNames).stream().toList();
        fieldNames = CollectionUtils.subtract(fieldNames, relationshipNames).stream().toList();
        if (CollectionUtils.isNotEmpty(fieldNames)) {
            UpdateWrapper<<%= persistClass %>> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("<%= primaryKey.fields[0].columnName %>", ids);
            fieldNames.forEach(fieldName -> updateWrapper.set(
                CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName),
                BeanUtil.getFieldValue(change<%= instanceType %>, fieldName)
            ));
            this.update(updateWrapper);
        } else if (CollectionUtils.isNotEmpty(relationshipNames)) {
            List<<%= persistClass%>> <%= entityInstance %>List = this.listByIds(ids);
            if (CollectionUtils.isNotEmpty(<%= entityInstance %>List)) {
                <%= entityInstance %>List.forEach(<%= entityInstance %> -> {
                    relationshipNames.forEach(relationName ->
                        BeanUtil.setFieldValue(<%= entityInstance %>, relationName,
                            BeanUtil.getFieldValue(<%= mapper%>.toEntity(change<%= instanceType %>), relationName)));
                    this.createOrUpdateAndRelatedRelations(<%= entityInstance %>, relationshipNames);
                });
            }
        }
        <%_ } _%>
    }
    <%_ if (fieldsContainParentAndChildren && !reactive) { _%>
    // 清除children缓存
    private void clearChildrenCache() {
        Objects.requireNonNull(cacheManager.getCache(<%= entityAbsolutePackage %>.domain.<%= entityClass %>.class.getName() + ".children"))
            .clear();
    }
    <%_ } _%>
    <%_ if (relationshipsForCache.length > 0 && !reactive) { _%>
    protected void clearRelationsCache() {
        this.relationCacheNames.forEach(
            cacheName -> Optional.ofNullable(cacheManager.getCache(cacheName)).ifPresent(Cache::clear)
        );
    }
    <%_ } _%>

    public void updateRelationships(List<String> otherEntityIds, String relationshipName, List<<%= primaryKey.type %>> relatedIds, String operateType) {
        <%_ if (ormTool === 'mybatis') { _%>
        relatedIds.forEach(id -> {
            <%= persistClass %> byId = getById(id);
            Binder.bindRelations(byId, relationNames.stream().filter(rel -> !rel.equals(relationshipName)).toArray(String[]::new));
            <%_ relationships.filter(relationship => !relationship.bcConfig.leftUnidirectional && relationship.relationshipRightSide && relationship.relationshipManyToMany).forEach( relationship => { _%>
            if (relationshipName.equals("<%= relationship.relationshipName %>")) {
                if (CollectionUtils.isNotEmpty(otherEntityIds)) {
                    <%_ if (relationship.otherEntity.primaryKey.type === 'String') { _%>
                    List<<%= relationship.otherEntity.primaryKey.type %>> ids = otherEntityIds;
                    <%_ } else if (relationship.otherEntity.primaryKey.type === 'Long' || relationship.otherEntity.primaryKey.type === 'Integer') { _%>
                    List<<%= relationship.otherEntity.primaryKey.type %>> ids = otherEntityIds.stream().map(<%= relationship.otherEntity.primaryKey.type %>::valueOf).toList();
                    <%_ } else if (relationship.otherEntity.primaryKey.type === 'UUID') { _%>
                    List<<%= relationship.otherEntity.primaryKey.type %>> ids = otherEntityIds.stream().map(UUID::fromString).toList();
                    <%_ } _%>
                    List<<%= relationship.otherEntity.persistClass %>> <%= relationship.otherEntity.persistInstance %>Exist = byId.get<%= relationship.relationshipNameCapitalized %>();
                    if (operateType.equals("add")) {
                        List<<%= relationship.otherEntity.primaryKey.type %>> collect = ids.stream().filter(relId -> <%= relationship.otherEntity.persistInstance %>Exist.stream().noneMatch(vp -> vp.getId().equals(relId))).toList();
                        if (CollectionUtils.isNotEmpty(collect)) {
                            collect.forEach(addId -> <%= relationship.otherEntity.persistInstance %>Exist.add(new <%= relationship.otherEntity.persistClass %>().id(addId)));
                            // 更新
                            this.createOrUpdateAndRelatedRelations(byId, List.of("<%= relationship.relationshipName %>"));
                        }
                    } else if (operateType.equals("delete")) {
                        List<<%= relationship.otherEntity.primaryKey.type %>> collect = ids.stream().filter(relId -> <%= relationship.otherEntity.persistInstance %>Exist.stream().anyMatch(vp -> vp.getId().equals(relId))).toList();
                        if (CollectionUtils.isNotEmpty(collect)) {
                            List<<%= relationship.otherEntity.persistClass %>> <%= relationship.otherEntity.persistInstance %>Add = <%= relationship.otherEntity.persistInstance %>Exist.stream().filter(vp -> !collect.contains(vp.getId())).toList();
                            byId.set<%= relationship.relationshipNameCapitalized %>(<%= relationship.otherEntity.persistInstance %>Add);
                            // 更新
                            this.createOrUpdateAndRelatedRelations(byId, List.of("<%= relationship.relationshipName %>"));
                        }
                    }
                }
            }
            <%_ }); %>
        });
        <%_ } _%>
    }

<%_ if (!dtoMapstruct && ormTool === 'mybatis') { _%>
    <%_ if (!serviceImpl) { _%>
    /**
     * Save and Get a <%= entityInstance %>.
     *
     * @param <%= instanceName %> the entity to save.
     * @return the persisted entity.
     */
    <%_ } _%>
    <%_ if (serviceImpl) { _%>
    @Override
    <%_ } _%>
    @Transactional
    public <% if (reactive) { %>Mono<<% } %><%= instanceType %><% if (reactive) { %>><% } %> saveAndGet(<%= instanceType %> <%= instanceName %>) {
        log.debug("Request to save <%= entityClass %> : {}", <%= instanceName %>);
        <%- include('../../_partials_entity_/mybatis_save_get_template', {viaService: false, returnDirectly: true, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false}); -%>
    }
<%_ } _%>
<%_ if (ormTool === 'mybatis' && sortFields && sortFields.length > 0) { _%>
    @Transactional
    public Boolean updateSortValue(<%= primaryKey.type %> id, <%= primaryKey.type %> beforeId, <%= primaryKey.type %> afterId, Integer changeSortValue, QueryWrapper<<%= entityClass%>> queryWrapper, SortValueOperateType type) {
        switch (type) {
            case VALUE: {
                if (ObjectUtils.isNotEmpty(changeSortValue)) {
                    return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, changeSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                } else {
                    return false;
                }
            }
            case STEP: {
                if (ObjectUtils.allNotNull(id, beforeId)) {
                    Set<<%= primaryKey.type %>> ids = new HashSet<>();
                    ids.add(id);
                    ids.add(beforeId);
                    Map<<%= primaryKey.type %>, Integer> idSortValueMap = listByIds(ids).stream()
                        .collect(Collectors.toMap(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, <%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>));
                    return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, idSortValueMap.get(beforeId)).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update() &&
                        lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, idSortValueMap.get(id)).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, beforeId).update();
                }else {
                    return false;
                }
            }
            case DROP:
            {
                Set<<%= primaryKey.type %>> ids = new HashSet<>();
                ids.add(id);
                if (ObjectUtils.isNotEmpty(beforeId)) {
                    ids.add(beforeId);
                }
                if (ObjectUtils.isNotEmpty(afterId)) {
                    ids.add(afterId);
                }
                Map<<%= primaryKey.type %>, Integer> idSortValueMap = listByIds(ids).stream()
                    .collect(Collectors.toMap(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, <%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>));
                if (ObjectUtils.allNotNull(beforeId, afterId)) {
                    // 计算中间值
                    Integer beforeSortValue = idSortValueMap.get(beforeId);
                    Integer afterSortValue = idSortValueMap.get(afterId);
                    Integer newSortValue = (beforeSortValue + afterSortValue) / 2;
                    if (!newSortValue.equals(afterSortValue) && !newSortValue.equals(beforeSortValue) ) {
                        // 正常值，保存到数据库。
                        return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, newSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                    } else {
                        // 没有排序值插入空间了，重新对相关的所有记录的排序值进行计算。然后再插入相关的值。
                        // 需要确定相应的记录范围
                        List<<%= entityClass %>> list = this.list(queryWrapper.orderByAsc("<%= sortFields[0].columnName %>"));
                        Integer newBeforeSortValue = 0;
                        Integer newAfterSortValue = 0;
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).set<%= sortFields[0].fieldNameCapitalized %>(100 * (i + 1));
                            if (afterId.equals(list.get(i).get<%= primaryKey.nameCapitalized %>())) {
                                newBeforeSortValue = list.get(i).get<%= sortFields[0].fieldNameCapitalized %>();
                            }
                            if (beforeId.equals(list.get(i).get<%= primaryKey.nameCapitalized %>())) {
                                newAfterSortValue = list.get(i).get<%= sortFields[0].fieldNameCapitalized %>();
                            }
                        }
                        newSortValue = (newBeforeSortValue + newAfterSortValue) / 2;
                        updateBatchById(list);
                        return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, newSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                    }
                } else if (ObjectUtils.isNotEmpty(beforeId)) {
                    // 计算比beforeId实体大的排序值
                    Integer beforeSortValue = idSortValueMap.get(beforeId);
                    Integer newSortValue = (beforeSortValue + 100) - (beforeSortValue + 100) % 100;
                    // 正常值，保存到数据库。
                    return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, newSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                } else if (ObjectUtils.isNotEmpty(afterId)) {
                    // 计算比afterId实体小的排序值
                    Integer afterSortValue = idSortValueMap.get(afterId);
                    Integer newSortValue = (afterSortValue - 100) - (afterSortValue - 100) % 100;
                    if (newSortValue <= 0) {
                        // 没有排序值插入空间了，重新对相关的所有记录的排序值进行计算。然后再插入相关的值。
                        // 需要确定相应的记录范围
                        List<<%= entityClass %>> list = this.list(queryWrapper.orderByAsc("<%= sortFields[0].columnName %>"));
                        Integer newBeforeSortValue = 0;
                        Integer newAfterSortValue = 0;
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).set<%= sortFields[0].fieldNameCapitalized %>(100 * (i + 1));
                            if (afterId.equals(list.get(i).getId())) {
                                newBeforeSortValue = list.get(i).get<%= sortFields[0].fieldNameCapitalized %>();
                            }
                            if (beforeId.equals(list.get(i).getId())) {
                                newAfterSortValue = list.get(i).get<%= sortFields[0].fieldNameCapitalized %>();
                            }
                        }
                        newSortValue = (newBeforeSortValue + newAfterSortValue) / 2;
                        updateBatchById(list);
                        return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, newSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                    } else {
                        // 正常值，保存到数据库。
                        return lambdaUpdate().set(<%= entityClass %>::get<%= sortFields[0].fieldNameCapitalized %>, newSortValue).eq(<%= entityClass %>::get<%= primaryKey.nameCapitalized %>, id).update();
                    }
                } else {
                    // todo 异常
                    return false;
                }
            }
            default:
                return false;
        }
    }
<%_ } _%>
<%_ if (extendData && ormTool === 'mybatis') { _%>
    /**
     * 保存拓展数据，包含字段和关联关系
     *
     * @param entity  指定实体的
     * @param extData 扩展数据
     */
    @Transactional
    public void saveExtData(<%= persistClass %> entity, Map<String, Object> extData) {
        String entityName = "<%= persistClass %>";
        // 先获得结构描述，然后保存到数据库
        Optional<CommonTable> commonTableOptional = this.commonTableRepository.findOneByEntityName(entityName).map(item -> {
            Binder.bindRelations(item, new String[]{"metaModel"});
            return item;
        });
        commonTableOptional.ifPresent(commonTable -> {
                List<CommonTableField> extendFields = commonTable
                    .getCommonTableFields()
                    .stream()
                    .filter(commonField -> !commonField.getSystem()).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(extendFields)) {
                    return;
                }
                String extTableName = commonTable.getTableName() + "_" + commonTable.getId() + "_ext";
                if (this.extDataRepository.existsByTableNameAndId(extTableName, entity.getId())) {
                    // 更新拓展字段
                    Map<String, Object> fieldsMap = new HashMap<>();
                    commonTable.getCommonTableFields().stream().filter(commonTableField -> !commonTableField.getSystem())
                            .forEach(commonTableField -> {
                                if (!commonTableField.getEntityFieldName().equals("id")) {
                                    fieldsMap.put(commonTableField.getTableColumnName(), extData.get(commonTableField.getEntityFieldName()));
                                }
                            });
                    // 更新拓展关联关系
                    for (CommonTableRelationship commonTableRelationship : commonTable.getRelationships()) {
                        if (!commonTableRelationship.getSystem()) {
                            if (commonTableRelationship.getRelationshipType().equals(RelationshipType.MANY_TO_ONE) || commonTableRelationship.getRelationshipType().equals(RelationshipType.ONE_TO_ONE)) {
                                String fieldName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                                fieldsMap.put(fieldName, extData.get(commonTableRelationship.getRelationshipName() + "Id"));
                            } else {
                                // 有中间表
                                String tableName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + commonTableRelationship.getOtherEntityName());
                                String relationshipFieldName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                                String otherEntityIdName = StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityName() + "Id");
                                Map<String, Object> relationFieldsMap = new HashMap<>();
                                relationFieldsMap.put(relationshipFieldName, entity.getId());
                                relationFieldsMap.put(otherEntityIdName, extData.get(otherEntityIdName));
                                this.extDataRepository.updateToManyRelationById(tableName, entity.getId(), relationFieldsMap);
                            }
                        }
                    }
                    if (!fieldsMap.isEmpty()) {
                        this.extDataRepository.updateToManyRelationById(extTableName, entity.getId(), fieldsMap);
                    }
                } else {
                    // insert拓展的字段数据
                    Map<String, Object> insertMap = new HashMap<>();
                    commonTable.getCommonTableFields().stream().filter(commonTableField -> !commonTableField.getSystem())
                            .forEach(field -> insertMap.put(field.getTableColumnName(), extData.get(field.getEntityFieldName())));
                    // insert拓展的关联数据
                    for (CommonTableRelationship commonTableRelationship : commonTable.getRelationships()) {
                        if (!commonTableRelationship.getSystem()) {
                            if (commonTableRelationship.getRelationshipType().equals(RelationshipType.MANY_TO_ONE) || commonTableRelationship.getRelationshipType().equals(RelationshipType.ONE_TO_ONE)) {
                                String fieldName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                                insertMap.put(fieldName, extData.get(commonTableRelationship.getRelationshipName() + "Id"));
                            } else {
                                // 有中间表
                                String jointTableName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + commonTableRelationship.getOtherEntityName());
                                String relationshipFieldName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                                String otherEntityIdName = StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityName() + "Id");
                                Map<String, Object> fieldsMap = new HashMap<>();
                                fieldsMap.put(relationshipFieldName, entity.getId());
                                fieldsMap.put(otherEntityIdName, extData.get(otherEntityIdName));
                                this.extDataRepository.insertToManyRelation(jointTableName, fieldsMap);
                            }
                        }
                    }
                    if (!insertMap.isEmpty()) {
                        insertMap.put("id", entity.getId());
                        this.extDataRepository.insertByMap(extTableName, insertMap);
                    }
                }
            }
        );
    }

    /**
     * 返回拓展内容Map，包括拓展字段和拓展关系
     *
     * @param entity 指定实体的
     * @return Map<String, Object>
     */
    private Map<String, Object> getExtData(<%= persistClass %> entity) {
        String entityName = "CommonTableRelationship";
        Map<String, Object> result = new HashMap<>();
        // 先获得结构描述
        Optional<CommonTable> commonTable = this.commonTableRepository.findOneByEntityName(entityName).map(item -> {
            Binder.bindRelations(item, new String[]{"metaModel"});
            return item;
        });
        Map<String, Object> fieldsMap = new HashMap<>();
        commonTable.ifPresent(table -> {
            String extTableName = table.getTableName() + "_" + table.getId() + "_ext";
            // 返回拓展字段内容
            table.getCommonTableFields().stream()
                .filter(commonField -> !commonField.getSystem())
                .forEach(field -> fieldsMap.put(field.getTableColumnName(), field.getEntityFieldName()));
            if (!fieldsMap.isEmpty()) {
                Map<String, Object> objectMap = extDataRepository.selectMapByIdAndColumns(extTableName, entity.getId(), fieldsMap);
                if (objectMap != null && !objectMap.isEmpty()) {
                    result.putAll(objectMap);
                }
            }
            // 返回拓展关联内容
            table.getRelationships().stream()
                .filter(commonTableRelationship -> !commonTableRelationship.getSystem())
                .forEach(commonTableRelationship -> {
                    Binder.bindRelations(commonTableRelationship, new String[]{"extData", "dataDictionaryNode"});
                    if (commonTableRelationship.getRelationshipType().equals(RelationshipType.ONE_TO_ONE) || commonTableRelationship.getRelationshipType().equals(RelationshipType.MANY_TO_ONE)) {
                        String relationIdName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                        String relationTitleName = StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityField());
                        String tableName = commonTableRelationship.getCommonTable().getTableName() + "_" + commonTableRelationship.getCommonTable().getId() + "_ext";
                        Optional<CommonTable> oneByEntityName = commonTableRepository.findOneByEntityName(commonTableRelationship.getOtherEntityName());
                        String joinTableName = oneByEntityName.get().getTableName();
                        fieldsMap.clear();
                        fieldsMap.put("a." + relationIdName, commonTableRelationship.getRelationshipName() + "Id");
                        fieldsMap.put("b." + relationTitleName, commonTableRelationship.getRelationshipName() + StrUtil.upperFirst(commonTableRelationship.getOtherEntityField()));
                        Map<String, Object> one = this.extDataRepository.selectMapByTableAndIdAndColumns(tableName, entity.getId(), fieldsMap, joinTableName, relationIdName);
                        if (one != null) {
                            result.putAll(one);
                        }
                    } else if (commonTableRelationship.getRelationshipType().equals(RelationshipType.ONE_TO_MANY) || commonTableRelationship.getRelationshipType().equals(RelationshipType.MANY_TO_MANY)) {
                        String relationIdName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + "Id");
                        String relationTitleName = StrUtil.toUnderlineCase(commonTableRelationship.getRelationshipName() + commonTableRelationship.getOtherEntityField());
                        String tableName = "RelationshipJhiExt";
                        String otherIdName = StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityName()) + "_id";
                        String joinTableName = commonTableRelationship.getCommonTable().getTableName();
                        String otherTableName = StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityName());
                        fieldsMap.clear();
                        fieldsMap.put("b.id", "id");
                        fieldsMap.put("b." + StrUtil.toUnderlineCase(commonTableRelationship.getOtherEntityField()), commonTableRelationship.getOtherEntityField());
                        List<Map<String, Object>> list = this.extDataRepository.selectMapsByTableAndIdAndColumns(entity.getId(), fieldsMap, joinTableName, otherTableName, relationIdName, otherIdName);
                        if (list != null && !list.isEmpty()) {
                            result.put(commonTableRelationship.getRelationshipName(), list);
                        }
                    }
                });
        });
        return result;
    }

    @Override
    public <%= persistClass %> bindExtData(<%= persistClass %> entity) {
        entity.setExtData(getExtData(entity));
        return entity;
    }

    @Override
    public List<<%= persistClass %>> bindExtData(List<<%= persistClass %>> entities) {
        entities.forEach(entity -> entity.setExtData(getExtData(entity)));
        return entities;
    }

<%_ } _%>

    // jhipster-needle-service-add-method - JHipster will add getters and setters here, do not remove
<%# add by begcode end %>
}
