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

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

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= entityAbsolutePackage %>.repository.base;<%# modify by begcode %>

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.HashMap;
<%_ if (anyFieldIsUUID) { _%>
import java.util.UUID;
<%_ } _%>
import java.util.stream.IntStream;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;

import <%= entityAbsolutePackage %>.domain.<%= persistClass %>;

/**
 * Utility repository to load bag relationships based on https://vladmihalcea.com/hibernate-multiplebagfetchexception/
 */
public class <%= entityClass %>RepositoryWithBagRelationshipsImpl implements <%= entityClass %>RepositoryWithBagRelationships {

    private static final String <%= primaryKey.name.toUpperCase() %>_PARAMETER = "<%= primaryKey.name %>";
    private static final String <%= entityInstancePlural.toUpperCase() %>_PARAMETER = "<%= entityInstancePlural %>";

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Optional<<%= persistClass %>> fetchBagRelationships(Optional<<%= persistClass %>> <%= entityInstance %>) {
        return <%= entityInstance %>
<%_ for (const relationship of relationships.filter(relationship => relationship.bagRelationship)) { _%>
            .map(this::fetch<%= relationship.relationshipNameCapitalizedPlural %>)
<%_ } _%>
        ;
    }

    @Override
    public Page<<%= persistClass %>> fetchBagRelationships(Page<<%= persistClass %>> <%= entityInstancePlural %>) {
        return new PageImpl<>(fetchBagRelationships(<%= entityInstancePlural %>.getContent()), <%= entityInstancePlural %>.getPageable(), <%= entityInstancePlural %>.getTotalElements());
    }

    @Override
    public List<<%= persistClass %>> fetchBagRelationships(List<<%= persistClass %>> <%= entityInstancePlural %>) {
        return Optional
            .of(<%= entityInstancePlural %>)
<%_ for (const relationship of relationships.filter(relationship => relationship.bagRelationship)) { _%>
            .map(this::fetch<%= relationship.relationshipNameCapitalizedPlural %>)
<%_ } _%>
            .orElse(Collections.emptyList());
    }
<%_ for (const relationship of relationships.filter(relationship => relationship.bagRelationship)) { _%>

    <%= persistClass %> fetch<%= relationship.relationshipNameCapitalizedPlural %>(<%= persistClass %> result) {
        return entityManager
            .createQuery(
                "select <%= entityInstance %> from <%= persistClass %> <%= entityInstance %> left join fetch <%= entityInstance %>.<%= relationship.relationshipFieldNamePlural %> where <%= entityInstance %>.<%= primaryKey.name %> = :<%= primaryKey.name %>",
                <%= persistClass %>.class
            )
            .setParameter(<%= primaryKey.name.toUpperCase() %>_PARAMETER, result.get<%= primaryKey.nameCapitalized %>())
            .getSingleResult();
    }

    List<<%= persistClass %>> fetch<%= relationship.relationshipNameCapitalizedPlural %>(List<<%= persistClass %>> <%= entityInstancePlural %>) {
        HashMap<Object, Integer> order = new HashMap<>();
        IntStream.range(0, <%= entityInstancePlural %>.size())
            .forEach(index -> order.put(<%= entityInstancePlural %>.get(index).get<%= primaryKey.nameCapitalized %>(), index));
        List<<%= persistClass %>> result = entityManager
            .createQuery(
                "select <%= entityInstance %> from <%= persistClass %> <%= entityInstance %> left join fetch <%= entityInstance %>.<%= relationship.relationshipFieldNamePlural %> where <%= entityInstance %> in :<%= entityInstancePlural %>",
                <%= persistClass %>.class
            )
            .setParameter(<%= entityInstancePlural.toUpperCase() %>_PARAMETER, <%= entityInstancePlural %>)
            .getResultList();
        Collections.sort(result, (o1, o2) -> Integer.compare(order.get(o1.get<%= primaryKey.nameCapitalized %>()), order.get(o2.get<%= primaryKey.nameCapitalized %>())));
        return result;
    }
<%_ } _%>
}
