<%#
 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 %>.web.rest.base;

<%_
const sortFields = fields.filter(field => field.options && field.options.sortField);
const pageName = ormTool !== 'mybatis' ? 'Page': 'IPage';
const pageType = ormTool !== 'mybatis' ? 'Pageable': 'Page';
const pageGetContent = ormTool !== 'mybatis' ? 'getContent': 'getRecords';
const pageUtil = ormTool !== 'mybatis' ? 'PaginationUtil': 'IPageUtil';
const viaService = !serviceNo;
const beans = []; // add by begcode
_%>
<%_ if (!dtoMapstruct || serviceNo) { _%>
import <%= entityAbsolutePackage %>.domain.<%= persistClass %>;
<%_ } _%>
import <%= packageName %>.aop.logging.AutoLog;
import <%= packageName %>.domain.enumeration.LogType;
import <%= packageName %>.domain.enumeration.OperateType;
import <%= entityAbsolutePackage %>.repository.<%= entityClass %>Repository;
<%_ if (!serviceNo) { _%>
import <%= entityAbsolutePackage %>.service.<%= entityClass %>Service;
<%_ } else { _%>
  <%_ if (isUsingMapsId === true) { _%>
import <%= entityAbsolutePackage %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository;
  <%_ } _%>
  <%_ if (searchEngineElasticsearch) { _%>
import <%= entityAbsolutePackage %>.repository.search.<%= entityClass %>SearchRepository;
  <%_ } _%>
<%_ } _%>
<%_ if (saveUserSnapshot) { _%>
import <%= entityAbsolutePackage %>.repository.UserRepository;
<%_ } _%>
import <%= packageName %>.web.rest.errors.BadRequestAlertException;
<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.web.rest.errors.ElasticsearchExceptionMapper;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>;
  <%_ if (serviceNo) { _%>
import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper;
  <%_ } _%>
<%_ } _%>
<%_ if (jpaMetamodelFiltering && !reactive) {  _%>
import <%= entityAbsolutePackage %>.service.criteria.<%= entityClass %>Criteria;
import <%= entityAbsolutePackage %>.service.<%= entityClass %>QueryService;
<%_ } else if (jpaMetamodelFiltering && reactive) { _%>
import <%= entityAbsolutePackage %>.domain.criteria.<%= entityClass %>Criteria;
<%_ } _%>

import tech.jhipster.web.util.HeaderUtil;
<%_ if (ormTool === 'mybatis' && sortFields && sortFields.length > 0) { %>
import org.apache.commons.lang3.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import <%= entityAbsolutePackage %>.domain.<%= entityClass %>;
import <%= packageName %>.domain.enumeration.SortValueOperateType;
<%_ } _%>
import org.apache.commons.collections4.CollectionUtils;
<%_ if (!paginationNo && (ormTool === 'hibernate' || searchEngineAny)) { _%>
import tech.jhipster.web.util.PaginationUtil;
<%_ } _%>
import tech.jhipster.web.util.<% if (reactive) { %>reactive.<% } %>ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
<%_ if (!paginationNo) { _%>
  <%_ if (ormTool === 'hibernate') { _%>
import org.springframework.data.domain.Page;
  <%_ } _%>
import org.springframework.data.domain.Pageable;
import tech.jhipster.web.util.PageRecord;
import <%= packageName %>.security.SecurityUtils;
  <%_ if (ormTool === 'mybatis') { _%>
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import <%= packageName %>.util.web.IPageUtil;
import <%= packageName %>.util.web.PageableUtils;
  <%_ } _%>
  <%_ if (reactive) { _%>
import org.springframework.data.domain.PageImpl;
  <%_ } _%>
  <%_ if (!reactive && ormTool === 'hibernate') { _%>
import org.springframework.data.jpa.domain.Specification;
  <%_ } _%>
import org.springframework.http.HttpHeaders;
  <%_ if (reactive) { _%>
import org.springframework.http.server.reactive.ServerHttpRequest;
  <%_ } _%>
  <%_ if (reactive) { _%>
import org.springframework.web.util.UriComponentsBuilder;
  <%_ } else { _%>
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  <%_ } _%>
<%_ } _%>
<%_ if (reactive || (!jpaMetamodelFiltering && !paginationNo)) { _%>
import org.springframework.http.HttpStatus;
<%_ } _%>
<%_ if (reactive) { _%>
import org.springframework.http.MediaType;
<%_ } _%>
import org.springframework.http.ResponseEntity;
<%_ if (databaseTypeSql && !viaService && (!saveUserSnapshot || isUsingMapsId)) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
<%_ if (reactive) { _%>
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpResponse;
<%_ } else { _%>
import <%= javaVersion === '17' ? 'jakarta' : 'javax'%>.servlet.http.HttpServletResponse;
<%_ } _%>

<%_ if (anyPropertyHasValidation) { _%>
import <%= javaVersion === '17' ? 'jakarta' : 'javax'%>.validation.Valid;
<%_ } _%>
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import <%= packageName %>.util.ExportUtil;
import java.text.SimpleDateFormat;

import org.apache.poi.ss.usermodel.Workbook;

<%_ if (anyPropertyHasValidation && !readOnly) { _%>
import <%= javaVersion === '17' ? 'jakarta' : 'javax'%>.validation.constraints.NotNull;
<%_ } _%>
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
<%_ if ((searchEngineAny || fieldsContainNoOwnerOneToOne) && !reactive) { _%>
  <%_ if (!viaService) { _%>
import java.util.stream.Collectors;
  <%_ } _%>
  <%_ if (!databaseTypeSql || !reactive) { _%>
import java.util.stream.StreamSupport;
  <%_ } _%>
<%_ } _%>
<%_ if (addCustomMethod.indexOf('rest') !== -1) { _%>
<%- include(`../../../_entityCustom_/${entityClass}.rest.ejs`, {position: 'import'}); -%>
<%_ } _%>
import io.swagger.v3.oas.annotations.Operation;

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

/**
<% if ((enableTranslation && nativeLanguage === 'zh-cn') || !enableTranslation ) { %>
 * 管理实体{@link <%= entityAbsoluteClass %>}的REST Controller。
<%_ } else { _%>
 * REST controller for managing {@link <%= entityAbsoluteClass %>}.
<%_ } _%>
 */
<%_ if (false) { _%>
@RestController
@RequestMapping("/api")
<%_ } _%>
<%_ if (databaseTypeSql && !viaService && !saveUserSnapshot) { _%>
@Transactional
<%_ } _%>
public class <%= entityClass %>BaseResource {

protected final Logger log = LoggerFactory.getLogger(<%= entityClass %>BaseResource.class);
<%_ if (!readOnly) { _%>

  <%_ let entityName = entityInstance;
  if (clientRootFolder && !skipUiGrouping) {
    entityName = this._.camelCase(`${clientRootFolder}${entityClass}`);
  } _%>
    protected static final String ENTITY_NAME = "<%= entityName %>";

    @Value("${jhipster.clientApp.name}")
    protected String applicationName;
<%_ } _%>
    <%_
    const instanceType = restClass;
    const instanceName = restInstance;
    const mapper = entityInstance  + 'Mapper';
    const entityToDtoReference = mapper + '::' + 'toDto';
    _%><% if (addCustomMethod.indexOf('rest') !== -1) { %><%- include(`../../../_entityCustom_/${entityClass}.construct.ejs`, {viaService: viaService,isController: true, beans: beans});-%><% } %><%- include('../../_partials_entity_/inject_template', {readOnly: readOnly, viaService: viaService, constructorName: entityClass + 'BaseResource', queryService: jpaMetamodelFiltering, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true, reactive: reactive, beans: beans}); -%>
<%_ if (!readOnly) { _%>
  <%_ if (!(skipRestApi && skipRestApi.indexOf('create') !== -1)) { _%>

    /**
     * {@code POST  /<%= entityApiUrl %>} : Create a new <%= entityInstance %>.
     *
     * @param <%= instanceName %> the <%= instanceName %> to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new <%= instanceName %>, or with status {@code 400 (Bad Request)} if the <%= entityInstance %> has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/<%= entityApiUrl %>")
    @Operation(tags = "新建<%= bcTitle%>", description = "创建并返回一个新的<%= bcTitle%>")
    @AutoLog(value = "新建<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.ADD)
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> create<%= entityClass %>(<% if (anyPropertyHasValidation) { %>@Valid <% } %>@RequestBody <%= instanceType %> <%= instanceName %>) throws URISyntaxException {
        log.debug("REST request to save <%= entityClass %> : {}", <%= instanceName %>);
        if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() != null) {
            throw new BadRequestAlertException("A new <%= entityInstance %> cannot already have an ID", ENTITY_NAME, "idexists");
        }
  <%_ if (saveUserSnapshot) { _%>
    <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %>
      <%_ if (userRelationship.collection) { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) {
            // Save users in case they are new and only exist in gateway
            userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>());
        }
      <%_ } else { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) {
            // Save user in case it's new and only exists in gateway
            userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>());
        }
      <%_ } _%>
    <% } %>
  <%_ } _%>
  <%_ if (!isUsingMapsId) { _%>
    <%_ for (field of primaryKey.fields.filter(f => f.autoGenerateByService)) { _%>
        <%= instanceName %>.set<%= field.fieldNameCapitalized %>(UUID.randomUUID());
    <%_ } _%>
  <%_ } _%>
  <%_ if (ormTool === 'mybatis' && serviceNo) { _%>
<%- include('/_global_partials_entity_/mybatis_save_get_template', {viaService: viaService, returnDirectly: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true}); -%>
  <%_ } else { _%>
<%- include('/_global_partials_entity_/save_template', {viaService: viaService, returnDirectly: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true}); -%>
  <%_ } _%>
  <%_ if (reactive) { _%>
            .map(result -> {
                try {
                    return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>()))
                        .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>))
                        .body(result);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            });
  <%_ } else { _%>
        return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>))
            .body(result);
  <%_ } _%>
    }
    <%_ } _%>

    /**
     * {@code PUT  /<%= entityApiUrl %>/:<%= primaryKey.name %>} : Updates an existing <%= entityInstance %>.
     *
     * @param <%= primaryKey.name %> the id of the <%= instanceName %> to save.
     * @param <%= instanceName %> the <%= instanceName %> to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated <%= instanceName %>,
     * or with status {@code 400 (Bad Request)} if the <%= instanceName %> is not valid,
     * or with status {@code 500 (Internal Server Error)} if the <%= instanceName %> couldn't be updated.
     */
    @PutMapping("/<%= entityApiUrl %>/{<%= primaryKey.name %>}")
    @Operation(tags = "更新<%= bcTitle%>", description = "根据主键更新并返回一个更新后的<%= bcTitle%>")
    @AutoLog(value = "更新<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.EDIT)
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> update<%= entityClass %>(
        @PathVariable(value = "<%= primaryKey.name %>", required = false) final <%= primaryKey.type %> <%= primaryKey.name %>,
        <% if (anyPropertyHasValidation) { %>@Valid <% } %>@RequestBody <%= instanceType %> <%= instanceName %>,
        @RequestParam(value = "batchIds", required = false) List<<%= primaryKey.type %>> batchIds,
        @RequestParam(value = "batchFields", required = false) List<String> batchFields
    ) {
        log.debug("REST request to update <%= entityClass %> : {}, {}", <%= primaryKey.name %>, <%= instanceName %>);
        if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(<%= primaryKey.name %>, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

  <%_ if (reactive) { _%>
        return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> {
            if (!exists) {
                return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"));
            }
  <%_ } else { _%>
      <%_ if (ormTool === 'hibernate') { _%>
        if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) {
      <%_ } else { _%>
        if (<%= entityInstance %>Repository.findById(<%= primaryKey.name %>).<%= javaVersion === '17' ? 'isEmpty()' : 'isPresent()'%>) {
      <%_ } _%>
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }
  <%_ } _%>

  <%_ if (saveUserSnapshot) { _%>
    <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %>
      <%_ if (userRelationship.collection) { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) {
            // Save users in case they are new and only exist in gateway
            userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>());
        }
      <%_ } else { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) {
            // Save user in case it's new and only exists in gateway
            userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>());
        }
      <%_ } _%>
    <% } %>
  <%_ } _%>
  <%_ if (ormTool === 'mybatis' && serviceNo) { _%>
<%- include('/_global_partials_entity_/mybatis_save_get_template', {viaService: viaService, returnDirectly: false, isUsingMapsId: false, mapsIdAssoc: mapsIdAssoc, isController: true}); -%>
  <%_ } else { _%>
<%- include('/_global_partials_entity_/update_template', {updatableEntity, viaService: viaService, returnDirectly: false, isUsingMapsId: false, mapsIdAssoc: mapsIdAssoc, isController: true, isPersisted: requiresPersistableImplementation}); -%>
  <%_ } _%>
  <%_ if (reactive) { _%>
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)))
            .map(result -> ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>))
                .body(result)
            );
        });
  <%_ } else { _%>
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>))
            .body(result);
  <%_ } _%>
    }
  <%_ if (ormTool === 'mybatis' && sortFields && sortFields.length > 0) { %>

    /**
     * {@code PUT  /<%= entityApiUrl %>/sort-value/:<%= primaryKey.name %>/:type} : Updates sort value <%= entityInstance %>.
     *
     * @param id the id of the <%= instanceName %> to update.
     * @param beforeId the previous id of current record.
     * @param afterId the later id of current record.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated <%= instanceName %>,
     * or with status {@code 400 (Bad Request)} if the <%= instanceName %> is not valid,
     * or with status {@code 500 (Internal Server Error)} if the <%= instanceName %> couldn't be updated.
     */
    @PutMapping("/<%= entityApiUrl %>/sort-value/{<%= primaryKey.name %>}/{type}")
    @Operation(tags = "更新排序字段值", description = "根据移动记录ID和插入点前后记录ID更新排序值")
    @AutoLog(value = "更新排序字段值", logType = LogType.OPERATE, operateType = OperateType.EDIT)
    public ResponseEntity<Boolean> updateSortValue(
        @PathVariable(value = "<%= primaryKey.name %>", required = false) final Long <%= primaryKey.name %>,
        @PathVariable(value = "type") SortValueOperateType type,
        @RequestParam(value = "beforeId", required = false) Long beforeId,
        @RequestParam(value = "afterId", required = false) Long afterId,
        @RequestParam(value = "newSortValue", required = false) Integer newSortValue,
        @RequestBody(required = false) <%= entityClass %>Criteria criteria
    ) {
        log.debug("REST request to update SortValue : {}, {}, {}", <%= primaryKey.name %>, beforeId, afterId);
        if (ObjectUtils.allNull(beforeId, afterId) && !type.equals(SortValueOperateType.VALUE)) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (<%= entityInstance %>Repository.findById(<%= primaryKey.name %>).isEmpty()) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }
        QueryWrapper<<%= entityClass%>> queryWrapper = null;
        if (type.equals(SortValueOperateType.DROP)) {
            queryWrapper = <%= entityInstance %>QueryService.createQueryWrapper(criteria);
        }
        Boolean result = <%= entityInstance %>Service.updateSortValue(<%= primaryKey.name %>, beforeId, afterId, newSortValue, queryWrapper, type);
        return ResponseEntity.ok().body(result);
    }
  <%_ } _%>
    /**
     * {@code PATCH  /<%= entityApiUrl %>/:<%= primaryKey.name %>} : Partial updates given fields of an existing <%= entityInstance %>, field will ignore if it is null
     *
     * @param <%= primaryKey.name %> the id of the <%= instanceName %> to save.
     * @param <%= instanceName %> the <%= instanceName %> to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated <%= instanceName %>,
     * or with status {@code 400 (Bad Request)} if the <%= instanceName %> is not valid,
     * or with status {@code 404 (Not Found)} if the <%= instanceName %> is not found,
     * or with status {@code 500 (Internal Server Error)} if the <%= instanceName %> couldn't be updated.
     */
    @PatchMapping(value = "/<%= entityApiUrl %>/{<%= primaryKey.name %>}", consumes = {"application/json", "application/merge-patch+json"})
    @Operation(tags = "部分更新<%= bcTitle%>", description = "根据主键及实体信息实现部分更新，值为null的属性将忽略，并返回一个更新后的<%= bcTitle%>")
    @AutoLog(value = "部分更新<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.EDIT)
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> partialUpdate<%= entityClass %>(
    @PathVariable(value = "<%= primaryKey.name %>", required = false) final <%= primaryKey.type %> <%= primaryKey.name %>,
    <% if (anyPropertyHasValidation) { %>@NotNull <% } %>@RequestBody <%= instanceType %> <%= instanceName %>) throws URISyntaxException {
        log.debug("REST request to partial update <%= entityClass %> partially : {}, {}", <%= primaryKey.name %>, <%= instanceName %>);
        if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(<%= primaryKey.name %>, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

  <%_ if (reactive) { _%>
        return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> {
            if (!exists) {
                return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"));
            }
  <%_ } else { _%>
      <%_ if (ormTool === 'hibernate') { _%>
        if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) {
      <%_ } else { _%>
        if (<%= entityInstance %>Repository.findById(<%= primaryKey.name %>).<%= javaVersion === '17' ? 'isEmpty' : 'isPresent'%>()) {
      <%_ } _%>
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }
  <%_ } _%>

  <%_ if (saveUserSnapshot) { _%>
    <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %>
      <%_ if (userRelationship.collection) { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) {
            // Save users in case they are new and only exist in gateway
            userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>());
        }
      <%_ } else { _%>
        if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) {
            // Save user in case it's new and only exists in gateway
            userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>());
        }
      <%_ } _%>
    <% } %>
  <%_ } _%>

            <%- include('../../_partials_entity_/patch_template', {isService: false, viaService: viaService}); -%>
  <%_ if (reactive) { _%>
            return result
                .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)))
                .map(res -> ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, res.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>))
                .body(res)
            );
        });
  <%_ } else { _%>
            return ResponseUtil.wrapOrNotFound(
                result,
                HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)
            );
  <%_ } _%>
    }
<%_ } _%>

    /**
     * {@code GET  /<%= entityApiUrl %>} : get all the <%= entityInstancePlural %>.
     *
<%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
  <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
  <%_ } _%>
<%_ } _%>
<%_ if (!jpaMetamodelFiltering && implementsEagerLoadApis) { _%>
     * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
<%_ } _%>
<%_ if (jpaMetamodelFiltering) { _%>
     * @param criteria the criteria which the requested entities should match.
<%_ } else if (fieldsContainNoOwnerOneToOne) { _%>
     * @param filter the filter of the request.
<%_ } _%>
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of <%= entityInstancePlural %> in body.
     */
<%_ if (reactive) { _%>
    @GetMapping(value = "/<%= entityApiUrl %>", produces = MediaType.APPLICATION_JSON_VALUE)
<%_ } else { _%>
    @GetMapping("/<%= entityApiUrl %>")
<%_ } _%>
    @Operation(tags = "获取<%= bcTitle%>分页列表", description = "获取<%= bcTitle%>的分页列表数据")
    @AutoLog(value = "获取<%= bcTitle%>分页列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
<%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
<%_ } _%>
<%- include('../../_partials_entity_/get_all_template', {viaService}); -%>
<%_ if (publicApiBy) { _%>
<%_ const publicApiByData = this._generatePublicApiBy(publicApiBy, fields, { packageName: packageName }); _%>

    /**
     * {@code GET  /<%= entityApiUrl %>/public} : get all public <%= entityInstancePlural %>.
     *
  <%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
    <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
    <%_ } _%>
  <%_ } _%>
  <%_ if (!jpaMetamodelFiltering && implementsEagerLoadApis) { _%>
     * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
  <%_ } _%>
  <%_ if (jpaMetamodelFiltering) { _%>
     * @param criteria the criteria which the requested entities should match.
  <%_ } else if (fieldsContainNoOwnerOneToOne) { _%>
     * @param filter the filter of the request.
  <%_ } _%>
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of <%= entityInstancePlural %> in body.
     */
  <%_ if (reactive) { _%>
    @GetMapping(value = "/<%= entityApiUrl %>/public", produces = MediaType.APPLICATION_JSON_VALUE)
  <%_ } else { _%>
    @GetMapping("/<%= entityApiUrl %>/public")
  <%_ } _%>
    @Operation(tags = "获取<%= bcTitle%>分页列表", description = "获取<%= bcTitle%>的分页列表数据")
    @AutoLog(value = "获取<%= bcTitle%>分页列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
  <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
  <%_ } _%>
<%- include('../../_partials_entity_/get_all_template_public', { viaService, publicApiByData: publicApiByData }); -%>

    /**
     * {@code GET  /<%= entityApiUrl %>/public/:id} : get the "id" <%= entityInstance %>.
     *
     * @param id the id of the <%= instanceName %> to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the <%= instanceName %>, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/<%= entityApiUrl %>/public/{id}")
    @Operation(tags = "获取指定主键的<%= bcTitle%>", description = "获取指定主键的<%= bcTitle%>信息")
    @AutoLog(value = "获取指定主键的<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.VIEW)
  <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
  <%_ } _%>
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> getPublic<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) {
        log.debug("REST request to get <%= entityClass %> : {}", id);<%- include('../../_partials_entity_/get_template', {viaService, returnDirectly:false, implementsEagerLoadApis}); -%>
        return ResponseUtil.wrapOrNotFound(<%= instanceName %>);
    }
<%_ } _%>
<%_ if (softDelete && !skipSoftDelete) { _%>

    /**
     * {@code GET  /<%= entityApiUrl %>/recycle-bin} : get all the <%= entityInstancePlural %>.
     *
  <%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
    <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
    <%_ } _%>
  <%_ } _%>
  <%_ if (!jpaMetamodelFiltering && implementsEagerLoadApis) { _%>
     * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
  <%_ } _%>
  <%_ if (jpaMetamodelFiltering) { _%>
     * @param criteria the criteria which the requested entities should match.
  <%_ } else if (fieldsContainNoOwnerOneToOne) { _%>
     * @param filter the filter of the request.
  <%_ } _%>
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of <%= entityInstancePlural %> in body.
     */
  <%_ if (reactive) { _%>
    @GetMapping(value = "/<%= entityApiUrl %>", produces = MediaType.APPLICATION_JSON_VALUE)
  <%_ } else { _%>
    @GetMapping("/<%= entityApiUrl %>/recycle-bin")
  <%_ } _%>
    @Operation(tags = "获取回收站中<%= bcTitle%>分页列表", description = "获取回收站中<%= bcTitle%>的分页列表数据")
    @AutoLog(value = "获取回收站中<%= bcTitle%>分页列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
  <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
  <%_ } _%>
<%- include('../../_partials_entity_/get_all_recycle_bin_template', {viaService}); -%>

    /**
     * {@code GET  /<%= entityApiUrl %>/recycle-bin/:id} : get the "id" <%= entityInstance %>.
     *
     * @param id the id of the <%= instanceName %> to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the <%= instanceName %>, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/<%= entityApiUrl %>/recycle-bin/{id}")
    @Operation(tags = "获取回收站中指定主键的<%= bcTitle%>", description = "获取回收站中指定主键的<%= bcTitle%>信息")
    @AutoLog(value = "获取回收站中指定主键的<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.VIEW)
<%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
<%_ } _%>
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> getByIdInRecycleBin(@PathVariable <%= primaryKey.type %> id) {
        log.debug("REST request to get <%= entityClass %> : {}", id);<%- include('../../_partials_entity_/get_recycle_bin_template', {viaService, returnDirectly:false, implementsEagerLoadApis}); -%>
        return ResponseUtil.wrapOrNotFound(<%= instanceName %>);
    }

    /**
    * {@code DELETE  /<%= entityApiUrl %>/recycle-bin/delete} : delete all the "ids" <%= entityClassPlural %>.
    *
    * @param ids the ids of the articleDTO to delete.
    * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
    */
    @DeleteMapping("/<%= entityApiUrl %>/recycle-bin/delete")
    @Operation(tags = "从回收站删除多个<%= bcTitle%>", description = "根据主键从回收站删除多个<%= bcTitle %>")
    @AutoLog(value = "从回收站删除多个<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.DELETE)
    public ResponseEntity<Void> deleteByIdsInRecycleBin(@RequestParam("ids") ArrayList<<%=primaryKey.type%>> ids) {
        log.debug("REST request to delete <%= entityClassPlural %> : {}", ids);
        <%= entityInstance %><% if (viaService) { %>Service.removeByIdsInRecycleBin<% } else { %>Repository.<%= ormTool === 'hibernate' ? 'delete' : 'deleteBatchIdsInRecycleBin'%><% } %>(ids);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, (ids != null ? ids.toString() : "NoIds"))).build();
    }

    /**
    * {@code RESTORE  /<%= entityApiUrl %>/recycle-bin/restore} : delete all the "ids" <%= entityClassPlural %>.
    *
    * @param ids the ids of the articleDTO to delete.
    * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
    */
    @PutMapping("/<%= entityApiUrl %>/recycle-bin/restore")
    @Operation(tags = "从回收站恢复多个<%= bcTitle%>", description = "根据主键从回收站恢复多个<%= bcTitle %>")
    @AutoLog(value = "从回收站恢复多个<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.DELETE)
    public ResponseEntity<Void> restore<%= entityClassPlural %>ByIds(@RequestParam("ids") ArrayList<<%=primaryKey.type%>> ids) {
        log.debug("REST request to delete <%= entityClassPlural %> : {}", ids);
        <%= entityInstance %><% if (viaService) { %>Service.restoreByIdsInRecycleBin<% } else { %>Repository.<%= ormTool === 'hibernate' ? 'delete' : 'restoreByIdsInRecycleBin'%><% } %>(ids);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, (ids != null ? ids.toString() : "NoIds"))).build();
    }

    /**
    * {@code DELETE  /<%= entityApiUrl %>/recycle-bin/empty} : delete all the "ids" <%= entityClassPlural %>.
    *
    * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
    */
    @DeleteMapping("/<%= entityApiUrl %>/recycle-bin/empty")
    @Operation(tags = "清空<%= bcTitle%>回收站", description = "清空<%= bcTitle%>回收站")
    @AutoLog(value = "清空<%= bcTitle%>回收站", logType = LogType.OPERATE, operateType = OperateType.DELETE)
    public ResponseEntity<Void> delete<%= entityClassPlural %>All() {
        log.debug("REST request to delete all.");
        <%= entityInstance %><% if (viaService) { %>Service.removeInRecycleBin<% } else { %>Repository.<%= ormTool === 'hibernate' ? 'delete' : 'deleteInRecycleBin'%><% } %>(null);
        return ResponseEntity.noContent().build();
    }
<%_ } _%>

<%_ if (!jpaMetamodelFiltering && reactive && paginationNo) { _%>
    /**
     * {@code GET  /<%= entityApiUrl %>} : get all the <%= entityInstancePlural %> as a stream.
     * @return the {@link Flux} of <%= entityInstancePlural %>.
     */
    @GetMapping(value = "/<%= entityApiUrl %>", produces = MediaType.APPLICATION_NDJSON_VALUE)
  <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
  <%_ } _%>
    public Flux<<%= instanceType %>> getAll<%= entityClassPlural %>AsStream() {
        log.debug("REST request to get all <%= entityClassPlural %> as a stream");
  <%_ if (viaService) { _%>
        return <%= entityInstance %>Service.findAll();
  <%_ } else { _%>
        return <%= entityInstance %>Repository.findAll()<%_ if (dtoMapstruct) { _%>.map(<%= entityToDtoReference %>)<%_ } _%>;
  <%_ } _%>
    }

<%_ } _%>
    /**
     * {@code GET  /<%= entityApiUrl %>/:id} : get the "id" <%= entityInstance %>.
     *
     * @param id the id of the <%= instanceName %> to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the <%= instanceName %>, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/<%= entityApiUrl %>/{id}")
    @Operation(tags = "获取指定主键的<%= bcTitle%>", description = "获取指定主键的<%= bcTitle%>信息")
    @AutoLog(value = "获取指定主键的<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.VIEW)
<%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
<%_ } _%>
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> get<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) {
        log.debug("REST request to get <%= entityClass %> : {}", id);<%- include('../../_partials_entity_/get_template', {viaService, returnDirectly:false, implementsEagerLoadApis}); -%>
        return ResponseUtil.wrapOrNotFound(<%= instanceName %>);
    }
<%_ if (!readOnly) { _%>

    /**
     * {@code DELETE  /<%= entityApiUrl %>/:id} : delete the "id" <%= entityInstance %>.
     *
     * @param id the id of the <%= instanceName %> to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/<%= entityApiUrl %>/{id}")
    @Operation(tags = "删除指定主键的<%= bcTitle%>", description = "删除指定主键的<%= bcTitle%>信息")
    @AutoLog(value = "删除指定主键的<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.DELETE)
    public <% if (reactive) { %>Mono<<% } %>ResponseEntity<Void><% if (reactive) { %>><% } %> delete<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) {
        log.debug("REST request to delete <%= entityClass %> : {}", id);
<%- include('../../_partials_entity_/delete_template', {viaService: viaService, fromResource: true}); -%>
  <%_ if (reactive) { _%>
    <%_ if (databaseTypeCouchbase) { _%>
            .then(Mono.just(ResponseEntity.noContent()
                .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build())
            );
    <%_ } else { %>
            .then(Mono.just(ResponseEntity.noContent()
                .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build())
        );
    <%_ } _%>
  <%_ } else { _%>
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (!primaryKey.fields[0].fieldTypeString) { %>.toString()<% } %>)).build();
  <%_ } _%>
    }
<%_ } _%>
<%_ if (searchEngineAny) { _%>

    /**
     * {@code SEARCH  /_search/<%= entityApiUrl %>?query=:query} : search for the <%= entityInstance %> corresponding
     * to the query.
     *
     * @param query the query of the <%= entityInstance %> search.
  <%_ if (!paginationNo) { _%>
     * @param pageable the pagination information.
    <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
    <%_ } _%>
  <%_ } _%>
     * @return the result of the search.
     */
    @Operation(tags = "全文检索<%= bcTitle%>", description = "根据关键字进行全文检索")
    @GetMapping("/_search/<%= entityApiUrl %>")<%- include('../../_partials_entity_/search_template', {viaService}); -%>
<%_ } _%>
<%_ if (!(skipRestApi && skipRestApi.indexOf('dataExport') !== -1)) { _%>

    /**
     * GET  /<%= entityApiUrl %>/export : export the <%= entityInstancePlural %>.
     *
     */
    @GetMapping("/<%= entityApiUrl %>/export")
    @Operation(tags = "<%= bcTitle%>EXCEL导出", description = "导出全部<%= bcTitle%>为EXCEL文件")
    @AutoLog(value = "<%= bcTitle%>EXCEL导出", logType = LogType.OPERATE, operateType = OperateType.EXPORT)
    public void exportToExcel(<%= reactive ? 'ServerHttpResponse' : 'HttpServletResponse'%> response) {
        <%_ if (viaService) { _%>
        <%= reactive ? 'Flux' : 'List' %><<%= instanceType %>> data<%= reactive ? 'Flux' : '' %> = <%= entityInstance %>Service.findAll(<% if (!paginationNo) { %><% if (ormTool !== 'mybatis') { %>Pageable.unpaged()<% } else { %><% if (viaService) { %>new Page<>(1, Integer.MAX_VALUE)<% } %><% } %><% } %>)<% if (!paginationNo) { %><% if (!reactive) { %>.<%= pageGetContent%>()<% } %><% } %>;
        <%_ } else { _%>
        <%= reactive ? 'Flux' : 'List' %><<%= instanceType %>> data<%= reactive ? 'Flux' : '' %> = <%= entityInstance %>Repository.findAll();
        <%_ } _%>
        <%_ if (reactive) { _%>
        dataFlux.collectList().doOnNext(data -> {
        <%_ } _%>
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("<%= bcTitle%>一览表","<%= bcTitle%>"),
            <%= instanceType %>.class, data);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = "<%= bcTitle%>_" + sdf.format(new Date()) + ".xlsx";
        try {
            ExportUtil.excel(workbook, filename, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        <%_ if (reactive) { _%>
        }).subscribe();
        <%_ } _%>
    }
<%_ } _%>
<%_ if (!(skipRestApi && skipRestApi.indexOf('dataImport') !== -1)) { _%>

    /**
     * POST  /<%= entityApiUrl %>/import : import the <%= entityInstancePlural %> from excel file.
     *
     * @return the ResponseEntity with status 200 (OK) and with body the <%= instanceName %>, or with status 404 (Not Found)
     */
    @PostMapping("/<%= entityApiUrl %>/import")
    @Operation(tags = "<%= bcTitle%>EXCEL导入", description = "根据<%= bcTitle%>EXCEL文件导入全部数据")
    @AutoLog(value = "<%= bcTitle%>EXCEL导入", logType = LogType.OPERATE, operateType = OperateType.IMPORT)
    public ResponseEntity<Void> exportToExcel(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<<%= instanceType %>> list = ExcelImportUtil.importExcel(file.getInputStream(), <%= instanceType %>.class, params);
        list.forEach(<%= entityInstance %><%= viaService ? 'Service' : 'Repository' %>::save);
        return ResponseEntity.ok().build();
    }
<%_ } _%>
<%_ if (fieldsContainParentAndChildren) { _%>

    /**
     * GET  /<%= entityApiUrl %>/tree : get all the <%= entityInstancePlural %> for parent is null.
     *<% if (!paginationNo) { %>
     * @param pageable the pagination information<% }  %>
     * @return the ResponseEntity with status 200 (OK) and the list of <%= entityInstancePlural %> in body
     */
    @GetMapping("/<%= entityApiUrl %>/tree")
    @Operation(tags = "获取<%= bcTitle%>树形列表", description = "获取<%= bcTitle%>的树形列表数据")
    @AutoLog(value = "获取<%= bcTitle%>树形列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
    <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
<%- include('../../_partials_entity_/get_tree_template', {viaService}); -%>

    /**
     * GET  /<%= entityApiUrl %>/{parentId}/tree : get all the <%= entityInstancePlural %> for parent is parentId.
     *<% if (!paginationNo) { %>
     * @param parentId the parent of Id <% }  %>
     * @return the ResponseEntity with status 200 (OK) and the list of <%= entityInstancePlural %> in body
     */
    @GetMapping("/<%= entityApiUrl %>/{parentId}/tree")
    @Operation(tags = "获取<%= bcTitle%>指定节点下的树形列表", description = "获取<%= bcTitle%>指定节点下的树形列表数据")
    @AutoLog(value = "获取<%= bcTitle%>指定节点下的树形列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
    <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%>
    @Transactional(readOnly = true)
    <%_ } _%>
    public <% if (reactive) { %>Mono<<% }%>ResponseEntity<List<<%= instanceType %>>><% if (reactive) { %>><% } %> getAll<%= entityClassPlural %>ofParent(@PathVariable <%= primaryKey.type %> parentId<% if (reactive) { %>, ServerHttpRequest request<% } %>) {
        log.debug("REST request to get all <%= entityClassPlural %> of parentId");
        <%_ if (!reactive) { _%>
        List<<%= dtoClass %>> list = <%= entityInstance %><%= viaService ? 'QueryService' : 'Repository' %>.findChildrenByParentId(parentId);
        return ResponseEntity.ok().body(list);
        <%_ } else { _%>
        return <%= entityInstance %><%= viaService ? 'Service.findChildrenByParentId' : 'Repository.findChildrenByParentId' %>(parentId).collectList()
                .map(result -> ResponseEntity.ok().body(result));
        <%_ } _%>
    }
<%_ } _%>
<%_ if (!readOnly) { _%>

    /**
    * {@code DELETE  /<%= entityApiUrl %>} : delete all the "ids" <%= entityClassPlural %>.
    *
    * @param ids the ids of the articleDTO to delete.
    * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
    */
    @DeleteMapping("/<%= entityApiUrl %>")
    @Operation(tags = "删除多个<%= bcTitle%>", description = "根据主键删除多个<%= bcTitle%>")
    @AutoLog(value = "删除多个<%= bcTitle%>", logType = LogType.OPERATE, operateType = OperateType.DELETE)
    public ResponseEntity<Void> delete<%= entityClassPlural %>ByIds(@RequestParam("ids") ArrayList<<%=primaryKey.type%>> ids) {
        log.debug("REST request to delete <%= entityClassPlural %> : {}", ids);
        if (ids != null) {
            ids.forEach(<%= entityInstance %><% if (viaService) { %>Service::delete<% } else { %>Repository::<%= ormTool === 'hibernate' ? 'delete' : 'deleteById'%><% } %>);
        }
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, (ids != null ? ids.toString() : "NoIds"))).build();
    }
<%_ } _%>
<%_ for (idx in relationships) { _%>
        <%_ if (relationships[idx].relationshipType === 'many-to-one' && relationships[idx].otherEntityName === 'user' && databaseTypeSql) { _%>
        <%_
            const pageInstance = ormTool !== 'mybatis' ? 'pageable' : 'PageableUtils.toPage(pageable)';
            const pageGetContent = ormTool !== 'mybatis' ? 'getContent': 'getRecords';
            const pageName = ormTool !== 'mybatis' ? 'Page': 'IPage';
            const pageUtil = ormTool !== 'mybatis' ? 'PaginationUtil': 'IPageUtil';
        _%>
    @Operation(tags = "查询<%= relationships[idx].relationshipName%>为当前用户的<%= bcTitle%>列表", description = "查询<%= relationships[idx].relationshipName%>为当前用户的<%= bcTitle%>列表")
    @GetMapping("/<%= entityApiUrl %>/<%= this._.kebabCase(relationships[idx].relationshipNameCapitalized)%>/current-user")
    public ResponseEntity<PageRecord<<%= instanceType %>>> findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser(<%= entityClass %>Criteria criteria<% if (!paginationNo) { %>, @org.springdoc.<%= javaVersion === '17' ? 'core' : 'api'%>.annotations.ParameterObject Pageable pageable<% if (reactive) { %>, ServerHttpRequest request<% } %><% } %>) {
        log.debug("REST request to get <%= entityClass %> for current user. ");
        <%= entityClass %>Criteria baseCriteria = new <%= entityClass %>Criteria();
        baseCriteria.<%= relationships[idx].relationshipName%>Id().setEquals(SecurityUtils.getCurrentUserId().orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>));
        baseCriteria.setAnd(criteria);
        <%= pageName%><<%= instanceType %>> page = <%= entityInstance %>QueryService.findByCriteria(criteria, <%- pageInstance%>);
        PageRecord<<%= instanceType %>> result = new PageRecord<>();
        result.records(page.<%= pageGetContent %>()).size(page.getSize()).total(page.getTotal()).page(<% if (ormTool === 'mybatis') { %>page.getCurrent()<% } else { _%>pageable.getPageNumber()<% } %>);
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(<% if (!reactive) { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } else { %>UriComponentsBuilder.fromHttpRequest(request)<% } %>, page);
        return ResponseEntity.ok().headers(headers).body(result);
    }
        <%_ } _%>
        <%_ if (relationships[idx].relationshipType === 'one-to-one' && relationships[idx].otherEntityName === 'user' && databaseTypeSql) { _%>
    @Operation(tags = "查询<%= relationships[idx].relationshipName%>为当前用户的<%= bcTitle%>列表", description = "查询<%= relationships[idx].relationshipName%>为当前用户的<%= bcTitle%>列表")
    @GetMapping("/<%= entityApiUrl %>/<%= this._.kebabCase(relationships[idx].relationshipNameCapitalized)%>/current-user")
    @AutoLog(value = "查询<%= relationships[idx].relationshipName%>为当前用户的<%= bcTitle%>列表", logType = LogType.OPERATE, operateType = OperateType.LIST)
    public ResponseEntity<<%= instanceType %>> findBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser() {
        Optional<<%= instanceType %>> result = <%= entityInstance %>Service.getBy<%= relationships[idx].relationshipNameCapitalized %>IsCurrentUser();
        return ResponseUtil.wrapOrNotFound(result);
    }
        <%_ } _%>
<%_ } _%>

    @GetMapping("/<%= entityApiUrl %>/stats")
    @Operation(tags = "根据条件对<%= bcTitle%>进行统计", description = "条件和统计的配置通过<%= bcTitle%>的Criteria类来实现")
    @AutoLog(value = "根据条件对<%= bcTitle%>进行统计", logType = LogType.OPERATE, operateType = OperateType.STATS)
    public ResponseEntity<List<Map<String, Object>>> stats(<%= entityClass %>Criteria criteria) {
        log.debug("REST request to get stats by criteria: {}", criteria);
        List<Map<String, Object>> statsMapList = <%= entityInstance %>QueryService.statsByAggregateCriteria(criteria);
        return ResponseEntity.ok().body(statsMapList);
    }

<%_ if (addCustomMethod.indexOf('rest') !== -1) { _%>
<%- include(`../../../_entityCustom_/${entityClass}.rest.ejs`, {position: 'method'}); -%>
<%_ } _%>

    // jhipster-needle-rest-resource-add-api - JHipster will add getters and setters here, do not remove

}
