2024-Java-704 / team_dev_A2_LibrarySystem

A2チームのリモートリポジトリ
0 stars 0 forks source link

ソートの修正 #190

Open kaneko-takumi-0130 opened 1 month ago

kaneko-takumi-0130 commented 1 month ago

ソートの修正

kiyota-teacher-2024-704 commented 1 month ago

セッション管理のデバック済

package com.example.demo.controller.children;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.demo.entity.Book;
import com.example.demo.repository.BookRepository;

import jakarta.servlet.http.HttpSession;

@Controller
public class ChildrenController {

    @Autowired
    private BookRepository bookRepository;

    @PostMapping("/user/childrenSearch")
    public String search(
            @RequestParam(name = "keyword", defaultValue = "") String keyword,
            Model model,
            HttpSession session) {

        // セッションから以前の検索結果を削除
        session.removeAttribute("searchResults");
        List<Book> bookList = new ArrayList<>();

        // キーワードがスペースを含む場合、複数条件で検索
        if (keyword.contains(" ")) {
            String[] keywords = keyword.split(" ");

            for (String key : keywords) {
                bookList.addAll(bookRepository.findByHuriganaContaining(key));
            }
        } else if (!keyword.isEmpty()) { // 単一条件で検索
            bookList.addAll(bookRepository.findByHuriganaContaining(keyword));
        }

        // 重複を削除
        List<Book> uniqueBookList = new ArrayList<>(new HashSet<>(bookList));

        // 検索結果をセッションに保存
        session.setAttribute("searchResults", uniqueBookList);

        // 書籍IDリストをカンマ区切りの文字列に変換してモデルに追加
        String bookIds = uniqueBookList.stream()
                .map(book -> book.getId().toString())
                .collect(Collectors.joining(","));
        model.addAttribute("bookIds", bookIds);
        model.addAttribute("books", uniqueBookList);

        return "/user/userSearch";
    }
}