Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

package com.example.librarysystem.controller; // import…

  1. User

    package com.example.librarysystem.controller; // import com.example.librarysystem.entity.BorrowRecord; import com.example.librarysystem.mapper.BorrowRecordsMapper; import com.example.librarysystem.service.BorrowRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;

    import java.util.HashMap; import java.util.List; import java.util.Map;

    @RestController @RequestMapping("/api/borrow-records") public class BorrowRecordController { @Autowired private BorrowRecordService borrowRecordService; @Autowired private BorrowRecordsMapper borrowRecordsMapper;

    @PostMapping("/borrow")
    public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
        try {
            BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
            return new ResponseEntity<>(savedRecord, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
    @GetMapping("/user/borrow-history/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
        List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
        System.out.println("Borrow history records: " + records);
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @GetMapping()
    public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
        List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @PostMapping("/return/{id}")
    public ResponseEntity<String> returnBook(@PathVariable Long id) {
        try {
            borrowRecordService.returnBook(id);
            return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
        } catch (Exception e) {
            return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/{id}")
    public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
        if (record!= null) {
            return new ResponseEntity<>(record, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
        borrowRecordService.deleteBorrowRecord(id);
        return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
    }
    
    @PostMapping("/edit")
    public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
        BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
        return new ResponseEntity<>(editedRecord, HttpStatus.OK);
    }
    

    } package com.example.librarysystem.controller;

    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.example.librarysystem.entity.Books;
    import com.example.librarysystem.mapper.BooksMapper;
    import com.example.librarysystem.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    
    @RestController
    @RequestMapping("/api/books")
    public class BookController {
        @Autowired
        private BookService bookService;
    
        @Autowired
        private BooksMapper booksMapper;
    
        // 添加图书的接口
        @PostMapping("/add")
        public ResponseEntity<?> addBook(@RequestBody Books book) {
            try {
                // 确保在此处获取有效内容
                if (book.getTitle() == null || book.getTitle().isEmpty()) {
                    return new ResponseEntity<>("书名不能为空", HttpStatus.BAD_REQUEST);
                }
                Books savedBook = bookService.addBook(book);
                return new ResponseEntity<>(savedBook, HttpStatus.OK);
            } catch (Exception e) {
                System.err.println("添加图书时出错: " + e.getMessage()); // 日志错误信息
                return new ResponseEntity<>("添加图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        // 根据书名删除图书的新接口
        @PostMapping("/deleteByTitle")
        public ResponseEntity<?> deleteBookByTitle(@RequestBody Map<String, String> map, @RequestHeader(value = "user-type", required = false) String userType) {
            if (!"admin".equals(userType)) {
    
    
                return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
            }
            String title = map.get("title");
            try {
                bookService.deleteBookByTitle(title);
                return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    
        @DeleteMapping("/{id}")
        public ResponseEntity<?> deleteBook(@PathVariable Long id, @RequestHeader(value = "user-type", required = false) String userType) {
            if (!"admin".equals(userType)) {
                return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
            }
            try {
                bookService.deleteBook(id);
                return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        @GetMapping("/{id}")
        public ResponseEntity<Books> getBookById(@PathVariable Long id) {
            Books book = bookService.getBookById(id);
    
            if (book == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
    
            return new ResponseEntity<>(book, HttpStatus.OK);
        }
        // 新增根据书名修改图书的接口
        @PostMapping("/editByTitle")
        public ResponseEntity<?> editBookByTitle(@RequestBody Map<String, String> map) {
            String oldTitle = map.get("oldTitle");
            String newTitle = map.get("newTitle");
            String newAuthor = map.get("newAuthor");
            String newYearPublishedStr = map.get("newYearPublished");
            int newYearPublished = 0;
            try {
                if (newYearPublishedStr!= null &&!newYearPublishedStr.isEmpty()) {
                    newYearPublished = Integer.parseInt(newYearPublishedStr);
                }
            } catch (NumberFormatException e) {
                return new ResponseEntity<>("出版年份格式错误", HttpStatus.BAD_REQUEST);
            }
            Books newBookInfo = new Books();
            newBookInfo.setTitle(newTitle);
            newBookInfo.setAuthor(newAuthor);
            newBookInfo.setYearPublished(newYearPublished);
            try {
                bookService.editBookByTitle(oldTitle, newBookInfo);
                return new ResponseEntity<>("Book edited successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("修改图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        @GetMapping("/all")
        public ResponseEntity<List<Books>> getBooks() {
            List<Books> books = bookService.getBooks();
            return new ResponseEntity<>(books, HttpStatus.OK);
        }
    
        @PostMapping("/edit")
        public ResponseEntity<?> editBook(@RequestBody Books book) {
            Books editedBook = bookService.editBook(book);
            return new ResponseEntity<>(editedBook, HttpStatus.OK);
        }
    
        @PostMapping("/search")
        public ResponseEntity<List<Books>> searchBooks(@RequestBody Map<String, String> map) {
            String keyword = map.get("keyword"); // 获取搜索关键字
            System.out.println("Searching for keyword: " + keyword); // 打印接收的关键词
    
            List<Books> booksList = null;
            try {
                if (keyword != null && !keyword.isEmpty()) {
                    booksList = booksMapper.selectList(Wrappers.<Books>lambdaQuery()
                            .like(Books::getTitle, keyword) // 模糊查询书名
                            .or()
                            .like(Books::getAuthor, keyword)); // 或者根据作者模糊查询
                    System.out.println("Total books found: " + booksList.size()); // 打印搜索到的书籍数量
                } else {
                    System.out.println("关键词为空");
                }
            } catch (Exception e) {
                booksList = Collections.emptyList(); // 如果出错,返回空列表
                System.err.println("Error during search: " + e.getMessage());
            }
    
            return new ResponseEntity<>(booksList, HttpStatus.OK);
        }
    }package com.example.librarysystem.entity;
    

    import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable;

    import lombok.Getter; import lombok.Setter;

    /**

    • @author xxx
    • @since 2024-12-23 */ @Getter @Setter

    public class Books implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    
    private String title;
    
    private String author;
    
    @TableField(value = "year_published")
    private Integer yearPublished;
    
    public Integer getYear_published(){
        return yearPublished;
    }
    
    
    public void setYear_published(Integer yearPublished){
        this.yearPublished = yearPublished;
    }
    

    } package com.example.librarysystem.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.time.LocalDateTime;

    import lombok.Getter; import lombok.Setter;

    /**

    • @author xxx
    • @since 2024-12-23 */ @Getter @Setter @TableName("borrow_records")

    public class BorrowRecord implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    
    private Integer userId;
    
    private Integer bookId;
    
    private LocalDateTime borrowDate;
    
    private String returnDate;
    
    private Boolean isReturned;
    
    private String status;
    

    } package com.example.librarysystem.mapper;

    import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.librarysystem.entity.BorrowRecord; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select;

    import java.util.List; import java.util.Map;

    /**

    • Mapper 接口
    • @author xxx
    • @since 2024-12-23 */ @Mapper public interface BorrowRecordsMapper extends BaseMapper { @Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " + "FROM borrow_records br " + "JOIN books b ON br.book_id = b.id " + "JOIN users u ON br.user_id = u.id " + "WHERE br.user_id = #{userId}") List<Map<String, Object>> findBorrowHistoryByUserId(Long userId); } package com.example.librarysystem.service; // import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.example.librarysystem.entity.BorrowRecord;

    import com.example.librarysystem.mapper.BorrowRecordsMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

    import java.time.LocalDateTime; import java.util.List;

    @Service public class BorrowRecordService { @Autowired private BorrowRecordsMapper borrowRecordMapper;

    public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
        if (borrowRecord.getBorrowDate() == null) {
            borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
        }
        borrowRecordMapper.insert(borrowRecord);
        return borrowRecord;
    }
    public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
        return borrowRecordMapper.selectList(
                Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
        );
    }
    public void returnBook(Long recordId) {
        BorrowRecord record = borrowRecordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("未找到借阅记录");
        }
    
        record.setIsReturned(true);
        record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
        borrowRecordMapper.updateById(record);
    }
    public List<BorrowRecord> getBorrowRecords() {
        return borrowRecordMapper.selectList(null);
    }
    
    public BorrowRecord getBorrowRecordById(Long id) {
        return borrowRecordMapper.selectById(id);
    }
    
    public void deleteBorrowRecord(Long id) {
        borrowRecordMapper.deleteById(id);
    }
    
    public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
    
        borrowRecordMapper.updateById(borrowRecord);
        return borrowRecord;
    }
    

    } package com.example.librarysystem.service;

    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.example.librarysystem.entity.Books;
    import com.example.librarysystem.mapper.BooksMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class BookService {
    
        @Autowired
        private BooksMapper bookMapper;
    
        public Books addBook(Books books) {
            try {
                // 可以添加日志打印出版年份的值,便于排查问题
                System.out.println("准备插入图书的出版年份: " + books.getYearPublished());
                bookMapper.insert(books);
                return books;
            } catch (Exception e) {
                throw new RuntimeException("图书插入数据库失败", e);
            }
        }
    
        public void deleteBook(Long id) {
            int rowsAffected = bookMapper.deleteById(id);
            if (rowsAffected == 0) {
                throw new RuntimeException("删除图书失败,可能该图书不存在或删除操作出现问题");
            }
        }
        public void deleteBookByTitle(String title) {
            Books book = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, title));
            if (book == null) {
                throw new RuntimeException("要删除的图书不存在");
            }
            int rowsAffected = bookMapper.deleteById(book.getId());
            if (rowsAffected == 0) {
                throw new RuntimeException("删除图书失败,可能删除操作出现问题");
            }
        }
        public List<Books> getBooks() {
            List<Books> booksList = bookMapper.selectList(null);
            for (Books book : booksList) {
                // 只在出版年份为 null 时设置默认值为 0,避免覆盖正确的出版年份
                if (book.getYearPublished() == null) {
                    book.setYearPublished(0);
                }
            }
            return booksList;
        }
        public Books getBookById(Long id) {
            return bookMapper.selectById(id);
        }
        public Books editBook(Books books) {
            if (books.getId() == null) {
                throw new RuntimeException("要修改的图书 id 不能为空");
            }
            // 检查图书是否存在
            Books existingBook = bookMapper.selectById(books.getId());
            if (existingBook == null) {
                throw new RuntimeException("要修改的图书不存在");
            }
            bookMapper.updateById(books);
            return books;
        }
        // 新增根据书名修改图书的方法
        public void editBookByTitle(String oldTitle, Books newBookInfo) {
    
            Books existingBook = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, oldTitle));
            if (existingBook == null) {
                throw new RuntimeException("要修改的图书不存在");
            }
            // 将找到的图书的信息更新为新的信息
            existingBook.setTitle(newBookInfo.getTitle());
            existingBook.setAuthor(newBookInfo.getAuthor());
            existingBook.setYearPublished(newBookInfo.getYearPublished());
            bookMapper.updateById(existingBook);
        }
    }<!DOCTYPE html>
    
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: center;
    }
    
    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }
    
    .book-list-container {
        margin-top: 20px;
    }
    
    .book-list-container h2 {
        margin-bottom: 20px;
    }
    
    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }
    
    .book-list-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .book-list-header input[type="checkbox"] {
        margin-right: 10px;
    }
    
    .book-list-container ul {
        list-style-type: none;
        padding: 0;
    }
    
    .book-list-container li {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }
    
    .book-item {
        display: flex;
        align-items: center;
        flex-grow: 1;
    }
    
    .book-actions {
        display: flex;
        align-items: center;
        margin-left: 10px;
    }
    
    .book-actions button {
        margin-left: 18px;
    }
    
    .user-list-container ul {
        list-style-type: none;
        padding: 0;
        width: 100%;
    }
    
    .user-list-container li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        margin-bottom: 10px;
    }
    
    .search-results-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        /* 卡片之间的间隔 */
        margin-top: 20px;
    }
    
    .book-card {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 20px;
        width: 350px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
    }
    
    .book-card:hover {
        transform: scale(1.05);
    }
    
    .book-card h3 {
        margin-top: 0;
    }
    
    .book-card p {
        margin: 5px 0;
    }
    
        </div>
    
    </div>
    <script>
        function logout() {
            alert('已退出登录');
            window.location.href = 'login.html';
        }
        function showForm(type, id = null) {
    
            const formContainer = document.getElementById('formContainer');
            const welcomeMessage = document.getElementById('welcomeMessage');
            formContainer.innerHTML = '';
            formContainer.style.display = 'block';
            welcomeMessage.style.display = 'none';
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>增加图书</h1>
                        <input type="text" placeholder="书名">
                        <input type="text" placeholder="作者">
                        <input type="number" placeholder="出版年份">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
                    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>删除图书</h1>
                        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
                    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>借阅记录</h1>
                        <div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
        <h1 style="text-align: center";>修改图书</h1>
        <input type="text" placeholder="旧书名" id="oldTitle">
        <input type="text" placeholder="新书名" id="newTitle">
        <input type="text" placeholder="新作者" id="newAuthor">
        <input type="number" placeholder="新出版年份" id="newYearPublished">
        <div style="text-align: center;">
        <button style="padding: 10px 20px; font-size: 16px;" onclick="editBookByTitle()">修改</button>
    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>查询图书</h1>
                        <input type="text" placeholder="搜索关键词" id="searchKeyword">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
                    `;
                    break;
                case 'userManagement':
                    loadUsers().then(users => {
                        const userItems = users.map(user => `
            <li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                <div class="book-actions">
                    <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                    <button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </li>`).join("");
    
                        formContainer.innerHTML = `
            <h1 style="text-align: center;">用户管理</h1>
            <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
                <ul style="list-style-type: none; padding: 0;">
                    ${userItems}
                </ul>
            </div>
        `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                    <h2 style="text-align: center";>借阅记录</h2>
                        <!-- 这里可以添加借阅记录的相关表单或内容 -->
                    `;
                    break;
                case 'editUser':
                    fetch(`http://localhost:8080/api/users/edit${id}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch user data');
                            }
                            return response.json();
                        })
                        .then(user => {
                            const formContainer = document.getElementById('formContainer');
                            formContainer.innerHTML = `
                <input type="hidden" value="${id}" name="id">
                <input type="text" placeholder="用户名" value="${user.username}" name="username">
                <input type="password" placeholder="密码" name="password">
                <select name="role">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                </select>
                <button onclick="editUser(${id})">保存</button>
            `;
                        })
                        .catch(error => {
                            console.error('获取用户数据出错:', error);
                            alert('获取用户数据失败: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
                    welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
            }
        }
    
        function deleteBookByTitle() {
            const bookTitle = document.getElementById('bookTitle').value; // 获取书名
            if (!bookTitle) {
                alert('请输入书名以进行删除');
                return;
            }
            fetch('http://localhost:8080/api/books/deleteByTitle', {  // 修改接口路径,对应后端新的删除接口
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ title: bookTitle })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
        function addBook() {
            const formContainer = document.getElementById('formContainer');
            const title = formContainer.querySelector('input[placeholder="书名"]').value;
            const author = formContainer.querySelector('input[placeholder="作者"]').value;
            const yearPublishedInput = formContainer.querySelector('input[placeholder="出版年份"]');
            const year_published_str = yearPublishedInput.value;
    
            let year_published;
            if (year_published_str.trim() === '') {
                alert('请输入出版年份');
                return;
            }
            if (!isNaN(Number(year_published_str))) {
                year_published = parseInt(year_published_str);
            } else {
                alert('出版年份输入格式不正确,请输入合法的数字');
                return;
            }
    
            fetch('http://localhost:8080/api/books/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 确保你有相应的权限
                },
                body: JSON.stringify({ title, author, yearPublished: year_published })
            })
                .then(response => {
                    if (response.ok) {
                        return response.json(); // 响应成功时解析 JSON
                    } else {
                        return response.text().then((text) => {
                            throw new Error(text); // 捕获非 2xx 响应
                        });
                    }
                })
                .then(data => {
                    alert('图书添加成功:' + data.title); // 显示添加成功的书名
                    loadBooks(); // 重新加载书籍
                    formContainer.innerHTML = ''; // 清空表单
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                    alert('添加图书失败:' + error.message); // 提示错误信息
                });
        }
        function searchBooks() {
            const keyword = document.getElementById('searchInput').value;
            if (keyword.trim() === '') {
                alert('请输入搜索关键词');
                return;
            }
    
            fetch('http://localhost:8080/api/books/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: keyword })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    displaySearchResults(data); // 传递返回的数据
                })
                .catch(error => console.error('Error:', error));
        }
    
        function displaySearchResults(books) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = ''; // 清空之前的结果
    
            if (books.length === 0) {
                searchResults.innerHTML = '<p>没有找到相关书籍</p>';
            } else {
                books.forEach(book => {
                    const listItem = document.createElement('div');
                    listItem.className = 'search-result-item';
                    listItem.innerHTML = `
                <div>
                    <strong>书名:</strong> ${book.title}<br>
                    <strong>作者:</strong> ${book.author}<br>
                    <strong>出版年份:</strong> ${book.yearPublished || '未知'}
                </div>
                <div class="book-actions">
                    <button onclick="borrowBook(${book.id})">借阅</button>
                    <button onclick="addToFavorites(${book.id})">添加到收藏</button>
                </div>
            `;
                    searchResults.appendChild(listItem);
                });
            }
        }
    
        function loadBooks() {
            console.log('Starting to load books...');
            return fetch('http://localhost:8080/api/books/all')
                .then(response => {
                    console.log('Received response from get-books:', response);
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log("获取到的图书列表详细信息:", books);
                    displayBooks(books);
                    return Promise.resolve();
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错:' + error.message);
                    return Promise.reject(error);
                });
        }
        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <div class="book-list-header">
                <input type="checkbox" id="selectAllBooks"> 全选
                <button onclick="deleteSelectedBooks()">删除选中</button>
            </div>
            <ul id="bookList">
    `;
            books.forEach(book => {
                let yearToShow = book.year_published;
                // 仅在year_published为null或undefined或为负数时设置为'暂无出版年份'
                if (yearToShow === null || yearToShow === undefined || yearToShow < 0) {
                    yearToShow = '暂无出版年份';
                }
                formContainer.innerHTML += `
    <li style="display: flex; align-items: center;">
        <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;">
            <input type="checkbox" class="bookCheckbox" value="${book.id}">
            <strong>书名:</strong> ${book.title} &nbsp;&nbsp;
            <strong>作者:</strong> ${book.author} &nbsp;&nbsp;
            <strong>出版年份:</strong> ${yearToShow}
        </div>
    <div class="book-actions">
        <button onclick="editBookForm('${book.id}')">编辑</button>
        <button onclick="deleteBook('${book.id}')">删除</button> <!-- 直接调用删除 -->
    </div>
    </li>
    

    ; }); formContainer.innerHTML += `;

            const selectAllCheckbox = document.getElementById('selectAllBooks');
            selectAllCheckbox.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.bookCheckbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
            bookCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }
        function deleteSelectedBooks() {
            const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
            const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);
    
            if (bookIds.length === 0) {
                alert('没有选中任何书籍。');
                return;
            }
    
            if (confirm('确定要删除选中的书籍吗?此操作不可撤销!')) {
                bookIds.forEach(id => {
                    deleteBook(id);
                });
            }
        }
    
    
        function loadUsers() {
            return fetch('http://localhost:8080/api/users/all')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(users => {
                    displayUsers(users);
                    return users;
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    alert('加载用户时出错:' + error.message);
                    // 可以考虑添加重试逻辑,比如延迟一段时间后重试
                    setTimeout(() => {
                        loadUsers();
                    }, 2000);
                    return [];
                });
        }
    
        function displayUsers(users) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">用户管理</h2>
        <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
            <ul style="list-style-type: none; padding: 0;">
                ${users.map(user => `
                    <li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                        <div class="book-actions">
                            <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                            <button onclick="deleteUser('${user.id}', '${user.username}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </div>
    `;
        }
        function loadBorrowRecords() {
            fetch('http://localhost:8080/api/borrow-records')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(records => {
                    displayBorrowRecords(records);
                })
                .catch(error => {
                    alert('加载借阅记录时出错:' + error.message);
                });
        }
    
        function displayBorrowRecords(records) {
    const borrowRecordsList = document.getElementById('borrowRecordsList');
    borrowRecordsList.innerHTML = '';
    
    if (records.length === 0) {
        borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
    } else {
        const table = document.createElement('table');
        table.innerHTML = `
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>作者</th>
                <th>借阅日期</th>
                <th>还书日期</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        `;
    
        records.forEach(record => {
            const borrowDate = new Date(record.borrow_date);
            const returnDate = record.return_date ? new Date(record.return_date) : '未还';
            const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
            const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
    
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.username || '未知'}</td>
                <td>${record.title || '未知'}</td>
                <td>${record.author || '未知'}</td>
                <td>${formattedBorrowDate}</td>
                <td>${formattedReturnDate}</td>
                <td>${record.is_returned ? '已还' : '未还'}</td>
                <td style="text-align: center;">
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
            table.appendChild(row);
        });
    
        borrowRecordsList.appendChild(table);
    }
    

    }

        function deleteUser(id) {
            if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                fetch(`http://localhost:8080/api/users/${id}`, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' }
                })
                    .then(response => {
                        if (response.status === 200) {
                            return response.text();
                        } else if (response.status === 404) {
                            throw new Error('用户不存在,无法删除');
                        } else {
                            throw new Error('删除用户时出现未知错误,状态码:' + response.status);
                        }
                    })
                    .then(data => {
                        alert('用户删除成功');
                        loadUsers(); // 重新加载用户列表
                    })
                    .catch(error => {
                        console.error('Error deleting user:', error);
                        alert('删除用户时出现错误:' + error.message);
                    });
            }
        }
        function editUserForm(id) {
            fetch(`http://localhost:8080/api/users/${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(user => {
                    console.log('获取到的用户信息:', user);
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                    <form id="editUserForm">
                        <input type="hidden" value="${id}" name="id">
                        <input type="text" placeholder="用户名" value="${user.username}" name="username">
                        <input type="password" placeholder="旧密码" name="oldPassword" required>
                        <input type="password" placeholder="新密码" name="newPassword">
                        <select name="role">
                            <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                        </select>
                        <button type="button" onclick="editUser(${id})">保存</button>
                        <button type="button" onclick="cancelEditUser()">取消</button>
                    </form>
                `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错:', error);
                    alert('获取用户信息失败,请稍后重试:' + error.message);
                });
        }
        function editUser(id) {
            const form = document.querySelector(`#editUserForm`);
            if (!form || !(form instanceof HTMLFormElement)) {
                return;
            }
            const formData = new FormData(form);
            // 处理可能存在格式问题的数据,比如去除密码字段前后空格
            formData.set('username', formData.get('username').trim());
            formData.set('oldPassword', formData.get('oldPassword').trim());
            formData.set('newPassword', formData.get('newPassword').trim());
            const data = Object.fromEntries(formData.entries());
    
            // 发送POST请求到/api/users/edit
            fetch('http://localhost:8080/api/users/edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        // 处理错误响应
                        return response.json().then(err => {
                            alert('编辑用户失败,原因:' + (err.message || '未知错误'));
                        });
                    }
                    return response.json(); // 假设成功响应也是JSON格式
                })
                .then(data => {
                    // 处理成功响应
                    alert(data.message || '用户信息更新成功');
                    loadUsers(); // 重新加载用户列表
                })
                .catch(error => {
                    console.error('Error editing user:', error);
                    alert('编辑用户信息时出错,请稍后重试:' + error.message);
                });
        }
        function editBookForm(bookId) {
            fetch(`http://localhost:8080/api/books/${bookId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('未能获取图书信息');
                    }
                    return response.json();
                })
                .then(book => {
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                <h2>修改图书</h2>
                <input type="hidden" value="${book.id}" id="bookId">
                <input type="text" placeholder="书名" id="newTitle" value="${book.title}">
                <input type="text" placeholder="作者" id="newAuthor" value="${book.author}">
                <input type="number" placeholder="出版年份" id="newYearPublished" value="${book.yearPublished}">
                <button onclick="editBook()">保存</button>
                <button onclick="cancelEditBook()">取消</button>
            `;
                })
                .catch(error => {
                    alert('获取图书信息失败,请稍后重试:' + error.message);
                });
        }
    
        function deleteBook(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }
            fetch(`http://localhost:8080/api/books/${bookId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 加上相应头,确认请求权限
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
    
        function editBook() {
            const bookId = document.getElementById('bookId').value;
            let newTitle = document.getElementById('newTitle').value;
            let newAuthor = document.getElementById('newAuthor').value;
            let newYearPublished = document.getElementById('newYearPublished').value;
    
            if (newTitle === '' || newAuthor === '' || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            const book = {
                id: parseInt(bookId),
                title: newTitle,
                author: newAuthor,
                year_published: parseInt(newYearPublished) // 确保使用合适的字段名称
            };
    
            fetch('http://localhost:8080/api/books/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 请确保权限设置
                },
                body: JSON.stringify(book)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书修改成功');
                    loadBooks(); // 刷新书籍列表
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function editBookByTitle() {
            const oldTitle = document.getElementById('oldTitle').value;
            const newTitle = document.getElementById('newTitle').value;
            const newAuthor = document.getElementById('newAuthor').value;
            const newYearPublished = document.getElementById('newYearPublished').value;
    
            if (!oldTitle || !newTitle || !newAuthor || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            fetch('http://localhost:8080/api/books/editByTitle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldTitle: oldTitle,
                    newTitle: newTitle,
                    newAuthor: newAuthor,
                    newYearPublished: newYearPublished
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement');
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!`)) {
                deleteBorrowRecord(recordId);
            }
        }
    
        function deleteBorrowRecord(recordId) {
            fetch(`http://localhost:8080/api/borrow-records/${recordId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('借阅记录删除成功');
                    loadBorrowRecords(); // 重新加载借阅记录
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错:' + error.message);
                });
        }
    
        // 获取当前管理员信息
        function fetchCurrentAdmin() {
            fetch('http://localhost:8080/admin/current')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log(data);
    
                    document.getElementById('adminName').textContent = `管理员:${data.username}`;
                })
                .catch(error => {
                    console.error('获取管理员名错误:', error);
                    document.getElementById('adminName').textContent = '管理员:未知'; // 出错时处理
                });
        }
    </script>
    

    import com.example.librarysystem.entity.Books; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper;

    /**

    • Mapper 接口
    • @author xxx
    • @since 2024-12-23

    */

    @Mapper public interface BooksMapper extends BaseMapper {

    } 借阅记录这样显示未知 未知 未知 Invalid Date 未还 未还 后端控制器显示JDBC Connection [HikariProxyConnection@813146093 wrapping com.mysql.cj.jdbc.ConnectionImpl@7fdcbb60] will not be managed by Spring ==> Preparing: SELECT id,user_id,book_id,borrow_date,return_date,is_returned,status FROM borrow_records ==> Parameters: <== Columns: id, user_id, book_id, borrow_date, return_date, is_returned, status <== Row: 62, 16, 118, 2024-12-25 02:54:16.807000, 2024-12-25T10:54:19.784, 1, null <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@58ae4f7d]

  2. Assistant

    From the information you've provided, it seems like you're dealing with a library management system where you're facing some issues with displaying borrow records. The borrow records are showing "未知" (unknown) for usernames, book titles, and authors, and there are also some date formatting issues indicated by "Invalid Date."

    Potential Causes and Solutions:

    1. Missing User and Book Information:

      • The issue with the borrow records showing "未知" (unknown) for usernames and book information might be due to the join operations not being able to find related data in the database. This could be because:
      • The user ID in the borrow_records table does not correspond to any user in the users table.
      • The book ID in the borrow_records table does not correspond to any book in the books table.

      Solution: Check your database entries for both users and books tables to ensure that all IDs referenced in the borrow_records table exist and are correct.

    2. Handling SQL Exceptions:

      • If there are exceptions occurring during the execution of your SQL queries that go unnoticed, the data may not be fetched correctly.

      Solution: Ensure your SQL exceptions are managed correctly, perhaps logging them or presenting a user-friendly message to indicate the issue.

    3. Date Formatting:

      • The "Invalid Date" issue indicates that dates might not be properly formatted or parsed when displaying them.

      Solution:

      • In your Java code where you are parsing or formatting dates, ensure that you use appropriate patterns.

      For example:

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      LocalDateTime dateTime = LocalDateTime.parse("2024-12-25 02:54:16", formatter);
      
    4. Check Join Logic:

      • Review the SQL SELECT statement used, particularly the joins that fetch the user and book details. It should look something like this:
      SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned 
      FROM borrow_records br 
      JOIN books b ON br.book_id = b.id 
      JOIN users u ON br.user_id = u.id 
      WHERE br.user_id = #{userId}
      
      • Ensure that it properly references the keys and relationships between your entities and that you have correct relationships defined in your database schema.
    5. Spring Transaction Management:

      • The message indicating that "JDBC Connection [HikariProxyConnection...] will not be managed by Spring" suggests that there may be issues with the transaction management in your Spring configuration.

      Solution: Ensure that your transactional annotations and configurations are set up correctly. Check your @Service and @Transactional annotations where applicable.

    Debugging Steps:

    • Database Inspection: Inspect the borrow_records, users, and books tables for consistency in references.
    • Logging: Add logging statements in your SQL execution methods to capture the query being run and any potential exceptions that are caught.
    • Temporary Outputs: Temporarily add extra outputs in your REST controller to see the actual values being returned before being sent to the client.

    Summary

    The problems you're encountering are mostly related to how data from different tables relates to each other along with how it’s being formatted and displayed. Make sure to check the relationships in your database's data and also the transaction configurations within your Spring application to ensure everything is wired up correctly.

    If you need help with a specific part of the SQL query or any configuration, please let me know!

  3. User

    上方代码翻译中文

  4. Assistant

    好的,以下是你提供代码的中文翻译和解析。根据你的代码,我将逐步描述各个部分的功能。

    BorrowRecordController (借阅记录控制器)

    @RestController
    @RequestMapping("/api/borrow-records")
    public class BorrowRecordController {
        @Autowired
        private BorrowRecordService borrowRecordService;
        @Autowired
        private BorrowRecordsMapper borrowRecordsMapper;
    
        @PostMapping("/borrow")
        public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
            try {
                BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
                return new ResponseEntity<>(savedRecord, HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        }
        
        @GetMapping("/user/borrow-history/{userId}")
        public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
            List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
            System.out.println("借阅历史记录: " + records);
            return new ResponseEntity<>(records, HttpStatus.OK);
        }
        
        @GetMapping()
        public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
            List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
            return new ResponseEntity<>(records, HttpStatus.OK);
        }
        
        @PostMapping("/return/{id}")
        public ResponseEntity<String> returnBook(@PathVariable Long id) {
            try {
                borrowRecordService.returnBook(id);
                return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
            } catch (Exception e) {
                return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        
        @GetMapping("/{id}")
        public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
            BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
            if (record != null) {
                return new ResponseEntity<>(record, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        }
    
        @DeleteMapping("/{id}")
        public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
            borrowRecordService.deleteBorrowRecord(id);
            return new ResponseEntity<>("借阅记录删除成功", HttpStatus.OK);
        }
    
        @PostMapping("/edit")
        public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
            BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
            return new ResponseEntity<>(editedRecord, HttpStatus.OK);
        }
    }
    

    翻译:

    • BorrowRecordController 类用于处理借书和还书的请求。
    • 提供借阅图书、用户借阅历史、获取所有借书记录、还书、查找具体借阅记录、删除借阅记录和编辑借阅记录的功能。
    • API 路径是 /api/borrow-records。

    BookController (图书控制器)

    @RestController
    @RequestMapping("/api/books")
    public class BookController {
        @Autowired
        private BookService bookService;
    
        @Autowired
        private BooksMapper booksMapper;
    
        @PostMapping("/add")
        public ResponseEntity<?> addBook(@RequestBody Books book) {
            try {
                if (book.getTitle() == null || book.getTitle().isEmpty()) {
                    return new ResponseEntity<>("书名不能为空", HttpStatus.BAD_REQUEST);
                }
                Books savedBook = bookService.addBook(book);
                return new ResponseEntity<>(savedBook, HttpStatus.OK);
            } catch (Exception e) {
                System.err.println("添加图书时出错: " + e.getMessage());
                return new ResponseEntity<>("添加图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        
        // 根据书名删除图书的新接口
        @PostMapping("/deleteByTitle")
        public ResponseEntity<?> deleteBookByTitle(@RequestBody Map<String, String> map, @RequestHeader(value = "user-type", required = false) String userType) {
            if (!"admin".equals(userType)) {
                return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
            }
            String title = map.get("title");
            try {
                bookService.deleteBookByTitle(title);
                return new ResponseEntity<>("图书删除成功", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    
        // 其他方法省略...
    }
    

    翻译:

    • BookController 类用于处理图书的相关请求,比如添加和删除图书。
    • 提供添加图书和通过书名删除图书的功能。
    • API 路径是 /api/books。

    Books (图书实体)

    @Getter
    @Setter
    public class Books implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @TableId(value = "id", type = IdType.AUTO)
        private Integer id;
    
        private String title;
        private String author;
    
        @TableField(value = "year_published")
        private Integer yearPublished;
    }
    

    翻译:

    • Books 是图书的实体类,包含图书的基本属性如书名、作者和出版年份。

    BorrowRecord (借阅记录实体)

    @Getter
    @Setter
    @TableName("borrow_records")
    public class BorrowRecord implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @TableId(value = "id", type = IdType.AUTO)
        private Long id;
    
        private Integer userId;
        private Integer bookId;
        private LocalDateTime borrowDate;
        private String returnDate;
        private Boolean isReturned;
    }
    

    翻译:

    • BorrowRecord 是借阅记录的实体类,保存借阅者 ID、书籍 ID、借阅日期、还书日期和是否已还等信息。

    数据库映射接口

    BooksMapper 和 BorrowRecordsMapper

    这两个接口分别映射图书和借阅记录的数据库操作,使用 MyBatis 框架简化数据库交互。

    HTML 部分 (管理员页面)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>管理员页面</title>
    </head>
    <body>
        <div class="topbar">
            <div id="adminName">管理员:</div>
            <button onclick="logout()">退出</button>
        </div>
    
        <div class="sidebar">
            <h1>管理员菜单</h1>
            <button onclick="showForm('add')">增加图书</button>
            <button onclick="showForm('delete')">删除图书</button>
            <button onclick="showForm('edit')">修改图书</button>
            <button onclick="showForm('search')">查询图书</button>
            <button onclick="showForm('userManagement')">用户管理</button>
            <button onclick="showForm('dataManagement')">图书管理</button>
            <button onclick="showForm('borrowRecords')">借阅记录</button>
        </div>
    
        <div class="main-content">
            <div class="welcome-message" id="welcomeMessage">
                <h1 style="text-align: center;">欢迎进入管理系统</h1>
            </div>
            <div class="form-container centered-content" id="formContainer" style="display:none;"></div>
        </div>
    </body>
    </html>
    

    翻译:

    • 此部分是管理员页面的前端代码,提供了一个简单的界面供管理员进行图书的增删改查(CRUD)操作以及查看借阅记录。
    • 页面包含管理员的名字、注销按钮、管理员菜单,以及动态显示的表单。

    总结

    本系统实现了图书借阅管理功能,包括图书的增加、删除、编辑和借阅记录的查看和管理。代码中每部分的功能都有详细注释,便于理解其目的和作用。

    如果你有任何具体代码部分需要进一步解释或翻译,请告诉我!

  5. User

    package com.example.librarysystem.controller; // import com.example.librarysystem.entity.BorrowRecord; import com.example.librarysystem.mapper.BorrowRecordsMapper; import com.example.librarysystem.service.BorrowRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;

    import java.util.HashMap; import java.util.List; import java.util.Map;

    @RestController @RequestMapping("/api/borrow-records") public class BorrowRecordController { @Autowired private BorrowRecordService borrowRecordService; @Autowired private BorrowRecordsMapper borrowRecordsMapper;

    @PostMapping("/borrow")
    public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
        try {
            BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
            return new ResponseEntity<>(savedRecord, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
    @GetMapping("/user/borrow-history/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
        List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
        System.out.println("Borrow history records: " + records);
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @GetMapping()
    public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
        List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @PostMapping("/return/{id}")
    public ResponseEntity<String> returnBook(@PathVariable Long id) {
        try {
            borrowRecordService.returnBook(id);
            return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
        } catch (Exception e) {
            return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/{id}")
    public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
        if (record!= null) {
            return new ResponseEntity<>(record, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
        borrowRecordService.deleteBorrowRecord(id);
        return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
    }
    
    @PostMapping("/edit")
    public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
        BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
        return new ResponseEntity<>(editedRecord, HttpStatus.OK);
    }
    

    }package com.example.librarysystem.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.time.LocalDateTime;

    import lombok.Getter; import lombok.Setter;

    /**

    • @author xxx
    • @since 2024-12-23 */ @Getter @Setter @TableName("borrow_records")

    public class BorrowRecord implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    
    private Integer userId;
    
    private Integer bookId;
    
    private LocalDateTime borrowDate;
    
    private String returnDate;
    
    private Boolean isReturned;
    
    private String status;
    

    } package com.example.librarysystem.mapper;

    import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.librarysystem.entity.BorrowRecord; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select;

    import java.util.List; import java.util.Map;

    /**

    • Mapper 接口
    • @author xxx
    • @since 2024-12-23 */ @Mapper public interface BorrowRecordsMapper extends BaseMapper { @Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " + "FROM borrow_records br " + "JOIN books b ON br.book_id = b.id " + "JOIN users u ON br.user_id = u.id " + "WHERE br.user_id = #{userId}") List<Map<String, Object>> findBorrowHistoryByUserId(Long userId); } package com.example.librarysystem.service; // import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.example.librarysystem.entity.BorrowRecord;

    import com.example.librarysystem.mapper.BorrowRecordsMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

    import java.time.LocalDateTime; import java.util.List;

    @Service public class BorrowRecordService { @Autowired private BorrowRecordsMapper borrowRecordMapper;

    public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
        if (borrowRecord.getBorrowDate() == null) {
            borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
        }
        borrowRecordMapper.insert(borrowRecord);
        return borrowRecord;
    }
    public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
        return borrowRecordMapper.selectList(
                Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
        );
    }
    public void returnBook(Long recordId) {
        BorrowRecord record = borrowRecordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("未找到借阅记录");
        }
    
        record.setIsReturned(true);
        record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
        borrowRecordMapper.updateById(record);
    }
    public List<BorrowRecord> getBorrowRecords() {
        return borrowRecordMapper.selectList(null);
    }
    
    public BorrowRecord getBorrowRecordById(Long id) {
        return borrowRecordMapper.selectById(id);
    }
    
    public void deleteBorrowRecord(Long id) {
        borrowRecordMapper.deleteById(id);
    }
    
    public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
    
        borrowRecordMapper.updateById(borrowRecord);
        return borrowRecord;
    }
    

    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: center;
    }
    
    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }
    
    .book-list-container {
        margin-top: 20px;
    }
    
    .book-list-container h2 {
        margin-bottom: 20px;
    }
    
    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }
    
    .book-list-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .book-list-header input[type="checkbox"] {
        margin-right: 10px;
    }
    
    .book-list-container ul {
        list-style-type: none;
        padding: 0;
    }
    
    .book-list-container li {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }
    
    .book-item {
        display: flex;
        align-items: center;
        flex-grow: 1;
    }
    
    .book-actions {
        display: flex;
        align-items: center;
        margin-left: 10px;
    }
    
    .book-actions button {
        margin-left: 18px;
    }
    
    .user-list-container ul {
        list-style-type: none;
        padding: 0;
        width: 100%;
    }
    
    .user-list-container li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        margin-bottom: 10px;
    }
    
    .search-results-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        /* 卡片之间的间隔 */
        margin-top: 20px;
    }
    
    .book-card {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 20px;
        width: 350px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
    }
    
    .book-card:hover {
        transform: scale(1.05);
    }
    
    .book-card h3 {
        margin-top: 0;
    }
    
    .book-card p {
        margin: 5px 0;
    }
    
        </div>
    
    </div>
    <script>
        function logout() {
            alert('已退出登录');
            window.location.href = 'login.html';
        }
        function showForm(type, id = null) {
    
            const formContainer = document.getElementById('formContainer');
            const welcomeMessage = document.getElementById('welcomeMessage');
            formContainer.innerHTML = '';
            formContainer.style.display = 'block';
            welcomeMessage.style.display = 'none';
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>增加图书</h1>
                        <input type="text" placeholder="书名">
                        <input type="text" placeholder="作者">
                        <input type="number" placeholder="出版年份">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
                    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>删除图书</h1>
                        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
                    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>借阅记录</h1>
                        <div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
        <h1 style="text-align: center";>修改图书</h1>
        <input type="text" placeholder="旧书名" id="oldTitle">
        <input type="text" placeholder="新书名" id="newTitle">
        <input type="text" placeholder="新作者" id="newAuthor">
        <input type="number" placeholder="新出版年份" id="newYearPublished">
        <div style="text-align: center;">
        <button style="padding: 10px 20px; font-size: 16px;" onclick="editBookByTitle()">修改</button>
    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>查询图书</h1>
                        <input type="text" placeholder="搜索关键词" id="searchKeyword">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
                    `;
                    break;
                case 'userManagement':
                    loadUsers().then(users => {
                        const userItems = users.map(user => `
            <li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                <div class="book-actions">
                    <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                    <button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </li>`).join("");
    
                        formContainer.innerHTML = `
            <h1 style="text-align: center;">用户管理</h1>
            <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
                <ul style="list-style-type: none; padding: 0;">
                    ${userItems}
                </ul>
            </div>
        `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                    <h2 style="text-align: center";>借阅记录</h2>
                        <!-- 这里可以添加借阅记录的相关表单或内容 -->
                    `;
                    break;
                case 'editUser':
                    fetch(`http://localhost:8080/api/users/edit${id}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch user data');
                            }
                            return response.json();
                        })
                        .then(user => {
                            const formContainer = document.getElementById('formContainer');
                            formContainer.innerHTML = `
                <input type="hidden" value="${id}" name="id">
                <input type="text" placeholder="用户名" value="${user.username}" name="username">
                <input type="password" placeholder="密码" name="password">
                <select name="role">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                </select>
                <button onclick="editUser(${id})">保存</button>
            `;
                        })
                        .catch(error => {
                            console.error('获取用户数据出错:', error);
                            alert('获取用户数据失败: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
                    welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
            }
        }
    
        function deleteBookByTitle() {
            const bookTitle = document.getElementById('bookTitle').value; // 获取书名
            if (!bookTitle) {
                alert('请输入书名以进行删除');
                return;
            }
            fetch('http://localhost:8080/api/books/deleteByTitle', {  // 修改接口路径,对应后端新的删除接口
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ title: bookTitle })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
        function addBook() {
            const formContainer = document.getElementById('formContainer');
            const title = formContainer.querySelector('input[placeholder="书名"]').value;
            const author = formContainer.querySelector('input[placeholder="作者"]').value;
            const yearPublishedInput = formContainer.querySelector('input[placeholder="出版年份"]');
            const year_published_str = yearPublishedInput.value;
    
            let year_published;
            if (year_published_str.trim() === '') {
                alert('请输入出版年份');
                return;
            }
            if (!isNaN(Number(year_published_str))) {
                year_published = parseInt(year_published_str);
            } else {
                alert('出版年份输入格式不正确,请输入合法的数字');
                return;
            }
    
            fetch('http://localhost:8080/api/books/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 确保你有相应的权限
                },
                body: JSON.stringify({ title, author, yearPublished: year_published })
            })
                .then(response => {
                    if (response.ok) {
                        return response.json(); // 响应成功时解析 JSON
                    } else {
                        return response.text().then((text) => {
                            throw new Error(text); // 捕获非 2xx 响应
                        });
                    }
                })
                .then(data => {
                    alert('图书添加成功:' + data.title); // 显示添加成功的书名
                    loadBooks(); // 重新加载书籍
                    formContainer.innerHTML = ''; // 清空表单
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                    alert('添加图书失败:' + error.message); // 提示错误信息
                });
        }
        function searchBooks() {
            const keyword = document.getElementById('searchInput').value;
            if (keyword.trim() === '') {
                alert('请输入搜索关键词');
                return;
            }
    
            fetch('http://localhost:8080/api/books/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: keyword })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    displaySearchResults(data); // 传递返回的数据
                })
                .catch(error => console.error('Error:', error));
        }
    
        function displaySearchResults(books) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = ''; // 清空之前的结果
    
            if (books.length === 0) {
                searchResults.innerHTML = '<p>没有找到相关书籍</p>';
            } else {
                books.forEach(book => {
                    const listItem = document.createElement('div');
                    listItem.className = 'search-result-item';
                    listItem.innerHTML = `
                <div>
                    <strong>书名:</strong> ${book.title}<br>
                    <strong>作者:</strong> ${book.author}<br>
                    <strong>出版年份:</strong> ${book.yearPublished || '未知'}
                </div>
                <div class="book-actions">
                    <button onclick="borrowBook(${book.id})">借阅</button>
                    <button onclick="addToFavorites(${book.id})">添加到收藏</button>
                </div>
            `;
                    searchResults.appendChild(listItem);
                });
            }
        }
    
        function loadBooks() {
            console.log('Starting to load books...');
            return fetch('http://localhost:8080/api/books/all')
                .then(response => {
                    console.log('Received response from get-books:', response);
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log("获取到的图书列表详细信息:", books);
                    displayBooks(books);
                    return Promise.resolve();
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错:' + error.message);
                    return Promise.reject(error);
                });
        }
        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <div class="book-list-header">
                <input type="checkbox" id="selectAllBooks"> 全选
                <button onclick="deleteSelectedBooks()">删除选中</button>
            </div>
            <ul id="bookList">
    `;
            books.forEach(book => {
                let yearToShow = book.year_published;
                // 仅在year_published为null或undefined或为负数时设置为'暂无出版年份'
                if (yearToShow === null || yearToShow === undefined || yearToShow < 0) {
                    yearToShow = '暂无出版年份';
                }
                formContainer.innerHTML += `
    <li style="display: flex; align-items: center;">
        <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;">
            <input type="checkbox" class="bookCheckbox" value="${book.id}">
            <strong>书名:</strong> ${book.title} &nbsp;&nbsp;
            <strong>作者:</strong> ${book.author} &nbsp;&nbsp;
            <strong>出版年份:</strong> ${yearToShow}
        </div>
    <div class="book-actions">
        <button onclick="editBookForm('${book.id}')">编辑</button>
        <button onclick="deleteBook('${book.id}')">删除</button> <!-- 直接调用删除 -->
    </div>
    </li>
    

    ; }); formContainer.innerHTML += `;

            const selectAllCheckbox = document.getElementById('selectAllBooks');
            selectAllCheckbox.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.bookCheckbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
            bookCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }
        function deleteSelectedBooks() {
            const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
            const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);
    
            if (bookIds.length === 0) {
                alert('没有选中任何书籍。');
                return;
            }
    
            if (confirm('确定要删除选中的书籍吗?此操作不可撤销!')) {
                bookIds.forEach(id => {
                    deleteBook(id);
                });
            }
        }
    
    
        function loadUsers() {
            return fetch('http://localhost:8080/api/users/all')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(users => {
                    displayUsers(users);
                    return users;
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    alert('加载用户时出错:' + error.message);
                    // 可以考虑添加重试逻辑,比如延迟一段时间后重试
                    setTimeout(() => {
                        loadUsers();
                    }, 2000);
                    return [];
                });
        }
    
        function displayUsers(users) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">用户管理</h2>
        <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
            <ul style="list-style-type: none; padding: 0;">
                ${users.map(user => `
                    <li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                        <div class="book-actions">
                            <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                            <button onclick="deleteUser('${user.id}', '${user.username}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </div>
    `;
        }
        function loadBorrowRecords() {
            fetch('http://localhost:8080/api/borrow-records')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(records => {
                    displayBorrowRecords(records);
                })
                .catch(error => {
                    alert('加载借阅记录时出错:' + error.message);
                });
        }
    
        function displayBorrowRecords(records) {
    const borrowRecordsList = document.getElementById('borrowRecordsList');
    borrowRecordsList.innerHTML = '';
    
    if (records.length === 0) {
        borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
    } else {
        const table = document.createElement('table');
        table.innerHTML = `
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>作者</th>
                <th>借阅日期</th>
                <th>还书日期</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        `;
    
        records.forEach(record => {
            const borrowDate = new Date(record.borrow_date);
            const returnDate = record.return_date ? new Date(record.return_date) : '未还';
            const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
            const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
    
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.username || '未知'}</td>
                <td>${record.title || '未知'}</td>
                <td>${record.author || '未知'}</td>
                <td>${formattedBorrowDate}</td>
                <td>${formattedReturnDate}</td>
                <td>${record.is_returned ? '已还' : '未还'}</td>
                <td style="text-align: center;">
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
            table.appendChild(row);
        });
    
        borrowRecordsList.appendChild(table);
    }
    

    }

        function deleteUser(id) {
            if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                fetch(`http://localhost:8080/api/users/${id}`, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' }
                })
                    .then(response => {
                        if (response.status === 200) {
                            return response.text();
                        } else if (response.status === 404) {
                            throw new Error('用户不存在,无法删除');
                        } else {
                            throw new Error('删除用户时出现未知错误,状态码:' + response.status);
                        }
                    })
                    .then(data => {
                        alert('用户删除成功');
                        loadUsers(); // 重新加载用户列表
                    })
                    .catch(error => {
                        console.error('Error deleting user:', error);
                        alert('删除用户时出现错误:' + error.message);
                    });
            }
        }
        function editUserForm(id) {
            fetch(`http://localhost:8080/api/users/${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(user => {
                    console.log('获取到的用户信息:', user);
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                    <form id="editUserForm">
                        <input type="hidden" value="${id}" name="id">
                        <input type="text" placeholder="用户名" value="${user.username}" name="username">
                        <input type="password" placeholder="旧密码" name="oldPassword" required>
                        <input type="password" placeholder="新密码" name="newPassword">
                        <select name="role">
                            <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                        </select>
                        <button type="button" onclick="editUser(${id})">保存</button>
                        <button type="button" onclick="cancelEditUser()">取消</button>
                    </form>
                `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错:', error);
                    alert('获取用户信息失败,请稍后重试:' + error.message);
                });
        }
        function editUser(id) {
            const form = document.querySelector(`#editUserForm`);
            if (!form || !(form instanceof HTMLFormElement)) {
                return;
            }
            const formData = new FormData(form);
            // 处理可能存在格式问题的数据,比如去除密码字段前后空格
            formData.set('username', formData.get('username').trim());
            formData.set('oldPassword', formData.get('oldPassword').trim());
            formData.set('newPassword', formData.get('newPassword').trim());
            const data = Object.fromEntries(formData.entries());
    
            // 发送POST请求到/api/users/edit
            fetch('http://localhost:8080/api/users/edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        // 处理错误响应
                        return response.json().then(err => {
                            alert('编辑用户失败,原因:' + (err.message || '未知错误'));
                        });
                    }
                    return response.json(); // 假设成功响应也是JSON格式
                })
                .then(data => {
                    // 处理成功响应
                    alert(data.message || '用户信息更新成功');
                    loadUsers(); // 重新加载用户列表
                })
                .catch(error => {
                    console.error('Error editing user:', error);
                    alert('编辑用户信息时出错,请稍后重试:' + error.message);
                });
        }
        function editBookForm(bookId) {
            fetch(`http://localhost:8080/api/books/${bookId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('未能获取图书信息');
                    }
                    return response.json();
                })
                .then(book => {
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                <h2>修改图书</h2>
                <input type="hidden" value="${book.id}" id="bookId">
                <input type="text" placeholder="书名" id="newTitle" value="${book.title}">
                <input type="text" placeholder="作者" id="newAuthor" value="${book.author}">
                <input type="number" placeholder="出版年份" id="newYearPublished" value="${book.yearPublished}">
                <button onclick="editBook()">保存</button>
                <button onclick="cancelEditBook()">取消</button>
            `;
                })
                .catch(error => {
                    alert('获取图书信息失败,请稍后重试:' + error.message);
                });
        }
    
        function deleteBook(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }
            fetch(`http://localhost:8080/api/books/${bookId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 加上相应头,确认请求权限
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
    
        function editBook() {
            const bookId = document.getElementById('bookId').value;
            let newTitle = document.getElementById('newTitle').value;
            let newAuthor = document.getElementById('newAuthor').value;
            let newYearPublished = document.getElementById('newYearPublished').value;
    
            if (newTitle === '' || newAuthor === '' || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            const book = {
                id: parseInt(bookId),
                title: newTitle,
                author: newAuthor,
                year_published: parseInt(newYearPublished) // 确保使用合适的字段名称
            };
    
            fetch('http://localhost:8080/api/books/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 请确保权限设置
                },
                body: JSON.stringify(book)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书修改成功');
                    loadBooks(); // 刷新书籍列表
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function editBookByTitle() {
            const oldTitle = document.getElementById('oldTitle').value;
            const newTitle = document.getElementById('newTitle').value;
            const newAuthor = document.getElementById('newAuthor').value;
            const newYearPublished = document.getElementById('newYearPublished').value;
    
            if (!oldTitle || !newTitle || !newAuthor || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            fetch('http://localhost:8080/api/books/editByTitle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldTitle: oldTitle,
                    newTitle: newTitle,
                    newAuthor: newAuthor,
                    newYearPublished: newYearPublished
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement');
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!`)) {
                deleteBorrowRecord(recordId);
            }
        }
    
        function deleteBorrowRecord(recordId) {
            fetch(`http://localhost:8080/api/borrow-records/${recordId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('借阅记录删除成功');
                    loadBorrowRecords(); // 重新加载借阅记录
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错:' + error.message);
                });
        }
    
        // 获取当前管理员信息
        function fetchCurrentAdmin() {
            fetch('http://localhost:8080/admin/current')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log(data);
    
                    document.getElementById('adminName').textContent = `管理员:${data.username}`;
                })
                .catch(error => {
                    console.error('获取管理员名错误:', error);
                    document.getElementById('adminName').textContent = '管理员:未知'; // 出错时处理
                });
        }
    </script>
    
  6. Assistant

    从你提供的信息看来,前端页面显示的借阅记录存在问题,具体表现为 用户名、书名 和 作者 显示为未知,以及 借阅日期 显示为 Invalid Date。同时,你提到前端网络请求可以获取到数据,这说明后端接口调用正常。以下是可能的原因及解决方案。

    可能的原因和解决方案

    1. 用户信息和书籍信息未正确联结:

      • 在后端的 SQL 查询语句中,通过用户 ID 和书籍 ID 来联结用户和书籍表。
      • 请确认 borrow_records 表中的 user_id 和 book_id 可以正确地加载对应的 users 和 books 表中的数据。

      例如,与借阅记录相关的 SQL 查询如下:

      SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned 
      FROM borrow_records br 
      JOIN books b ON br.book_id = b.id 
      JOIN users u ON br.user_id = u.id 
      WHERE br.user_id = #{userId}
      
      • 请确保:
        • borrow_records 表中存在的 userId 对应于 users 表中存在的 id。
        • borrow_records 表中的 bookId 对应于 books 表中的 id。

      解决方案:检查数据库中 users 和 books 表的数据,确保关联是正确的。

    2. 前端未正确处理数据:

      • 前端用于显示借阅记录的代码可能未正确解析来自服务器的响应数据,或者数据结构不符合预期。

      假设后端返回的数据结构如下:

      [
          {
              "id": 62,
              "userId": 16,
              "bookId": 118,
              "borrowDate": "2024-12-25T02:54:16.807",
              "returnDate": "2024-12-25T10:54:19.784",
              "isReturned": true,
              "status": null
          }
      ]
      
      • 你需要根据从后端返回的数据来显示相应的用户名和书名。

      解决方案:确保你在前端获取到完整的借阅记录信息,包括用户信息和书籍信息。例如,你可以在前端的 displayBorrowRecords 函数中根据获取的数据填充表格。

    3. Invalid Date 问题:

      • Invalid Date 显示可能是因为对日期的解析存在问题。确保你的日期字段格式符合 JavaScript 的 Date 对象创建要求。
      const borrowDate = new Date(record.borrow_date); // 确保 borrow_date 字符串格式正确
      const returnDate = record.return_date ? new Date(record.return_date) : '未还';
      
      • 确保 borrow_date 和 return_date 字段的格式是 ISO 8601 (yyyy-mm-ddThh:mm:ss.sssZ),这样 Date 对象才能正确解析。

      解决方案:你可以在 Java 后端中确保在插入和更新数据库时,日期的格式正确。

    4. 更新前端展示逻辑:

      • 确保在前端的 displayBorrowRecords 函数中,有适当的用于显示借阅关联信息的代码逻辑。

      示例代码:

      function displayBorrowRecords(records) {
          const borrowRecordsList = document.getElementById('borrowRecordsList');
          borrowRecordsList.innerHTML = '';
      
          if (records.length === 0) {
              borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
          } else {
              const table = document.createElement('table');
              table.innerHTML = `
                  <tr>
                      <th>用户名</th>
                      <th>书名</th>
                      <th>作者</th>
                      <th>借阅日期</th>
                      <th>还书日期</th>
                      <th>状态</th>
                      <th>操作</th>
                  </tr>
              `;
      
              records.forEach(record => {
                  const borrowDate = new Date(record.borrowDate);
                  const returnDate = record.returnDate ? new Date(record.returnDate) : '未还';
                  const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
                  const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
      
                  const row = document.createElement('tr');
                  row.innerHTML = `
                      <td>${record.username || '未知'}</td>
                      <td>${record.title || '未知'}</td>
                      <td>${record.author || '未知'}</td>
                      <td>${formattedBorrowDate}</td>
                      <td>${formattedReturnDate}</td>
                      <td>${record.isReturned ? '已还' : '未还'}</td>
                      <td style="text-align: center;">
                          <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                      </td>
                  `;
                  table.appendChild(row);
              });
      
              borrowRecordsList.appendChild(table);
          }
      }
      

    总结

    请逐步检查上述几点来解决你所遇到问题。确保数据库中的数据能正常被前端调用,同时及时处理和格式化日期。若依旧存在问题,可以在具体代码段中再进行细致调试,或直接在控制台中查看打印出来的构造数据,以此找到问题所在。

  7. User
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: center;
    }
    
    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }
    
    .book-list-container {
        margin-top: 20px;
    }
    
    .book-list-container h2 {
        margin-bottom: 20px;
    }
    
    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }
    
    .book-list-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .book-list-header input[type="checkbox"] {
        margin-right: 10px;
    }
    
    .book-list-container ul {
        list-style-type: none;
        padding: 0;
    }
    
    .book-list-container li {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }
    
    .book-item {
        display: flex;
        align-items: center;
        flex-grow: 1;
    }
    
    .book-actions {
        display: flex;
        align-items: center;
        margin-left: 10px;
    }
    
    .book-actions button {
        margin-left: 18px;
    }
    
    .user-list-container ul {
        list-style-type: none;
        padding: 0;
        width: 100%;
    }
    
    .user-list-container li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        margin-bottom: 10px;
    }
    
    .search-results-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        /* 卡片之间的间隔 */
        margin-top: 20px;
    }
    
    .book-card {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 20px;
        width: 350px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
    }
    
    .book-card:hover {
        transform: scale(1.05);
    }
    
    .book-card h3 {
        margin-top: 0;
    }
    
    .book-card p {
        margin: 5px 0;
    }
    
        </div>
    
    </div>
    <script>
        function logout() {
            alert('已退出登录');
            window.location.href = 'login.html';
        }
        function showForm(type, id = null) {
    
            const formContainer = document.getElementById('formContainer');
            const welcomeMessage = document.getElementById('welcomeMessage');
            formContainer.innerHTML = '';
            formContainer.style.display = 'block';
            welcomeMessage.style.display = 'none';
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>增加图书</h1>
                        <input type="text" placeholder="书名">
                        <input type="text" placeholder="作者">
                        <input type="number" placeholder="出版年份">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
                    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>删除图书</h1>
                        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
                    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>借阅记录</h1>
                        <div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
        <h1 style="text-align: center";>修改图书</h1>
        <input type="text" placeholder="旧书名" id="oldTitle">
        <input type="text" placeholder="新书名" id="newTitle">
        <input type="text" placeholder="新作者" id="newAuthor">
        <input type="number" placeholder="新出版年份" id="newYearPublished">
        <div style="text-align: center;">
        <button style="padding: 10px 20px; font-size: 16px;" onclick="editBookByTitle()">修改</button>
    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>查询图书</h1>
                        <input type="text" placeholder="搜索关键词" id="searchKeyword">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
                    `;
                    break;
                case 'userManagement':
                    loadUsers().then(users => {
                        const userItems = users.map(user => `
            <li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                <div class="book-actions">
                    <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                    <button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </li>`).join("");
    
                        formContainer.innerHTML = `
            <h1 style="text-align: center;">用户管理</h1>
            <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
                <ul style="list-style-type: none; padding: 0;">
                    ${userItems}
                </ul>
            </div>
        `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                    <h2 style="text-align: center";>借阅记录</h2>
                        <!-- 这里可以添加借阅记录的相关表单或内容 -->
                    `;
                    break;
                case 'editUser':
                    fetch(`http://localhost:8080/api/users/edit${id}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch user data');
                            }
                            return response.json();
                        })
                        .then(user => {
                            const formContainer = document.getElementById('formContainer');
                            formContainer.innerHTML = `
                <input type="hidden" value="${id}" name="id">
                <input type="text" placeholder="用户名" value="${user.username}" name="username">
                <input type="password" placeholder="密码" name="password">
                <select name="role">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                </select>
                <button onclick="editUser(${id})">保存</button>
            `;
                        })
                        .catch(error => {
                            console.error('获取用户数据出错:', error);
                            alert('获取用户数据失败: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
                    welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
            }
        }
    
        function deleteBookByTitle() {
            const bookTitle = document.getElementById('bookTitle').value; // 获取书名
            if (!bookTitle) {
                alert('请输入书名以进行删除');
                return;
            }
            fetch('http://localhost:8080/api/books/deleteByTitle', {  // 修改接口路径,对应后端新的删除接口
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ title: bookTitle })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
        function addBook() {
            const formContainer = document.getElementById('formContainer');
            const title = formContainer.querySelector('input[placeholder="书名"]').value;
            const author = formContainer.querySelector('input[placeholder="作者"]').value;
            const yearPublishedInput = formContainer.querySelector('input[placeholder="出版年份"]');
            const year_published_str = yearPublishedInput.value;
    
            let year_published;
            if (year_published_str.trim() === '') {
                alert('请输入出版年份');
                return;
            }
            if (!isNaN(Number(year_published_str))) {
                year_published = parseInt(year_published_str);
            } else {
                alert('出版年份输入格式不正确,请输入合法的数字');
                return;
            }
    
            fetch('http://localhost:8080/api/books/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 确保你有相应的权限
                },
                body: JSON.stringify({ title, author, yearPublished: year_published })
            })
                .then(response => {
                    if (response.ok) {
                        return response.json(); // 响应成功时解析 JSON
                    } else {
                        return response.text().then((text) => {
                            throw new Error(text); // 捕获非 2xx 响应
                        });
                    }
                })
                .then(data => {
                    alert('图书添加成功:' + data.title); // 显示添加成功的书名
                    loadBooks(); // 重新加载书籍
                    formContainer.innerHTML = ''; // 清空表单
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                    alert('添加图书失败:' + error.message); // 提示错误信息
                });
        }
        function searchBooks() {
            const keyword = document.getElementById('searchInput').value;
            if (keyword.trim() === '') {
                alert('请输入搜索关键词');
                return;
            }
    
            fetch('http://localhost:8080/api/books/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: keyword })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    displaySearchResults(data); // 传递返回的数据
                })
                .catch(error => console.error('Error:', error));
        }
    
        function displaySearchResults(books) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = ''; // 清空之前的结果
    
            if (books.length === 0) {
                searchResults.innerHTML = '<p>没有找到相关书籍</p>';
            } else {
                books.forEach(book => {
                    const listItem = document.createElement('div');
                    listItem.className = 'search-result-item';
                    listItem.innerHTML = `
                <div>
                    <strong>书名:</strong> ${book.title}<br>
                    <strong>作者:</strong> ${book.author}<br>
                    <strong>出版年份:</strong> ${book.yearPublished || '未知'}
                </div>
                <div class="book-actions">
                    <button onclick="borrowBook(${book.id})">借阅</button>
                    <button onclick="addToFavorites(${book.id})">添加到收藏</button>
                </div>
            `;
                    searchResults.appendChild(listItem);
                });
            }
        }
    
        function loadBooks() {
            console.log('Starting to load books...');
            return fetch('http://localhost:8080/api/books/all')
                .then(response => {
                    console.log('Received response from get-books:', response);
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log("获取到的图书列表详细信息:", books);
                    displayBooks(books);
                    return Promise.resolve();
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错:' + error.message);
                    return Promise.reject(error);
                });
        }
        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <div class="book-list-header">
                <input type="checkbox" id="selectAllBooks"> 全选
                <button onclick="deleteSelectedBooks()">删除选中</button>
            </div>
            <ul id="bookList">
    `;
            books.forEach(book => {
                let yearToShow = book.year_published;
                // 仅在year_published为null或undefined或为负数时设置为'暂无出版年份'
                if (yearToShow === null || yearToShow === undefined || yearToShow < 0) {
                    yearToShow = '暂无出版年份';
                }
                formContainer.innerHTML += `
    <li style="display: flex; align-items: center;">
        <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;">
            <input type="checkbox" class="bookCheckbox" value="${book.id}">
            <strong>书名:</strong> ${book.title} &nbsp;&nbsp;
            <strong>作者:</strong> ${book.author} &nbsp;&nbsp;
            <strong>出版年份:</strong> ${yearToShow}
        </div>
    <div class="book-actions">
        <button onclick="editBookForm('${book.id}')">编辑</button>
        <button onclick="deleteBook('${book.id}')">删除</button> <!-- 直接调用删除 -->
    </div>
    </li>
    

    ; }); formContainer.innerHTML += `;

            const selectAllCheckbox = document.getElementById('selectAllBooks');
            selectAllCheckbox.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.bookCheckbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
            bookCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }
        function deleteSelectedBooks() {
            const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
            const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);
    
            if (bookIds.length === 0) {
                alert('没有选中任何书籍。');
                return;
            }
    
            if (confirm('确定要删除选中的书籍吗?此操作不可撤销!')) {
                bookIds.forEach(id => {
                    deleteBook(id);
                });
            }
        }
    
    
        function loadUsers() {
            return fetch('http://localhost:8080/api/users/all')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(users => {
                    displayUsers(users);
                    return users;
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    alert('加载用户时出错:' + error.message);
                    // 可以考虑添加重试逻辑,比如延迟一段时间后重试
                    setTimeout(() => {
                        loadUsers();
                    }, 2000);
                    return [];
                });
        }
    
        function displayUsers(users) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">用户管理</h2>
        <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
            <ul style="list-style-type: none; padding: 0;">
                ${users.map(user => `
                    <li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                        <div class="book-actions">
                            <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                            <button onclick="deleteUser('${user.id}', '${user.username}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </div>
    `;
        }
        function loadBorrowRecords() {
            fetch('http://localhost:8080/api/borrow-records')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(records => {
                    displayBorrowRecords(records);
                })
                .catch(error => {
                    alert('加载借阅记录时出错:' + error.message);
                });
        }
    
        function displayBorrowRecords(records) {
    const borrowRecordsList = document.getElementById('borrowRecordsList');
    borrowRecordsList.innerHTML = '';
    
    if (records.length === 0) {
        borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
    } else {
        const table = document.createElement('table');
        table.innerHTML = `
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>作者</th>
                <th>借阅日期</th>
                <th>还书日期</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        `;
    
        records.forEach(record => {
            const borrowDate = new Date(record.borrowDate);
            const returnDate = record.returnDate ? new Date(record.returnDate) : '未还';
            const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
            const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
    
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.id || '未知'}</td>
                <td>${record.userId || '未知'}</td>
                <td>${record.bookId || '未知'}</td>
                <td>${formattedBorrowDate}</td>
                <td>${formattedReturnDate}</td>
                <td>${record.isReturned ? '已还' : '未还'}</td>
                <td style="text-align: center;">
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
            table.appendChild(row);
        });
    
        borrowRecordsList.appendChild(table);
    }
    

    }

        function deleteUser(id) {
            if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                fetch(`http://localhost:8080/api/users/${id}`, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' }
                })
                    .then(response => {
                        if (response.status === 200) {
                            return response.text();
                        } else if (response.status === 404) {
                            throw new Error('用户不存在,无法删除');
                        } else {
                            throw new Error('删除用户时出现未知错误,状态码:' + response.status);
                        }
                    })
                    .then(data => {
                        alert('用户删除成功');
                        loadUsers(); // 重新加载用户列表
                    })
                    .catch(error => {
                        console.error('Error deleting user:', error);
                        alert('删除用户时出现错误:' + error.message);
                    });
            }
        }
        function editUserForm(id) {
            fetch(`http://localhost:8080/api/users/${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(user => {
                    console.log('获取到的用户信息:', user);
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                    <form id="editUserForm">
                        <input type="hidden" value="${id}" name="id">
                        <input type="text" placeholder="用户名" value="${user.username}" name="username">
                        <input type="password" placeholder="旧密码" name="oldPassword" required>
                        <input type="password" placeholder="新密码" name="newPassword">
                        <select name="role">
                            <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                        </select>
                        <button type="button" onclick="editUser(${id})">保存</button>
                        <button type="button" onclick="cancelEditUser()">取消</button>
                    </form>
                `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错:', error);
                    alert('获取用户信息失败,请稍后重试:' + error.message);
                });
        }
        function editUser(id) {
            const form = document.querySelector(`#editUserForm`);
            if (!form || !(form instanceof HTMLFormElement)) {
                return;
            }
            const formData = new FormData(form);
            // 处理可能存在格式问题的数据,比如去除密码字段前后空格
            formData.set('username', formData.get('username').trim());
            formData.set('oldPassword', formData.get('oldPassword').trim());
            formData.set('newPassword', formData.get('newPassword').trim());
            const data = Object.fromEntries(formData.entries());
    
            // 发送POST请求到/api/users/edit
            fetch('http://localhost:8080/api/users/edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        // 处理错误响应
                        return response.json().then(err => {
                            alert('编辑用户失败,原因:' + (err.message || '未知错误'));
                        });
                    }
                    return response.json(); // 假设成功响应也是JSON格式
                })
                .then(data => {
                    // 处理成功响应
                    alert(data.message || '用户信息更新成功');
                    loadUsers(); // 重新加载用户列表
                })
                .catch(error => {
                    console.error('Error editing user:', error);
                    alert('编辑用户信息时出错,请稍后重试:' + error.message);
                });
        }
        function editBookForm(bookId) {
            fetch(`http://localhost:8080/api/books/${bookId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('未能获取图书信息');
                    }
                    return response.json();
                })
                .then(book => {
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                <h2>修改图书</h2>
                <input type="hidden" value="${book.id}" id="bookId">
                <input type="text" placeholder="书名" id="newTitle" value="${book.title}">
                <input type="text" placeholder="作者" id="newAuthor" value="${book.author}">
                <input type="number" placeholder="出版年份" id="newYearPublished" value="${book.yearPublished}">
                <button onclick="editBook()">保存</button>
                <button onclick="cancelEditBook()">取消</button>
            `;
                })
                .catch(error => {
                    alert('获取图书信息失败,请稍后重试:' + error.message);
                });
        }
    
        function deleteBook(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }
            fetch(`http://localhost:8080/api/books/${bookId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 加上相应头,确认请求权限
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
    
        function editBook() {
            const bookId = document.getElementById('bookId').value;
            let newTitle = document.getElementById('newTitle').value;
            let newAuthor = document.getElementById('newAuthor').value;
            let newYearPublished = document.getElementById('newYearPublished').value;
    
            if (newTitle === '' || newAuthor === '' || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            const book = {
                id: parseInt(bookId),
                title: newTitle,
                author: newAuthor,
                year_published: parseInt(newYearPublished) // 确保使用合适的字段名称
            };
    
            fetch('http://localhost:8080/api/books/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 请确保权限设置
                },
                body: JSON.stringify(book)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书修改成功');
                    loadBooks(); // 刷新书籍列表
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function editBookByTitle() {
            const oldTitle = document.getElementById('oldTitle').value;
            const newTitle = document.getElementById('newTitle').value;
            const newAuthor = document.getElementById('newAuthor').value;
            const newYearPublished = document.getElementById('newYearPublished').value;
    
            if (!oldTitle || !newTitle || !newAuthor || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            fetch('http://localhost:8080/api/books/editByTitle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldTitle: oldTitle,
                    newTitle: newTitle,
                    newAuthor: newAuthor,
                    newYearPublished: newYearPublished
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement');
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!`)) {
                deleteBorrowRecord(recordId);
            }
        }
    
        function deleteBorrowRecord(recordId) {
            fetch(`http://localhost:8080/api/borrow-records/${recordId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('借阅记录删除成功');
                    loadBorrowRecords(); // 重新加载借阅记录
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错:' + error.message);
                });
        }
    
        // 获取当前管理员信息
        function fetchCurrentAdmin() {
            fetch('http://localhost:8080/admin/current')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log(data);
    
                    document.getElementById('adminName').textContent = `管理员:${data.username}`;
                })
                .catch(error => {
                    console.error('获取管理员名错误:', error);
                    document.getElementById('adminName').textContent = '管理员:未知'; // 出错时处理
                });
        }
    </script>
    

    import com.example.librarysystem.mapper.BorrowRecordsMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

    import java.time.LocalDateTime; import java.util.List;

    @Service public class BorrowRecordService { @Autowired private BorrowRecordsMapper borrowRecordMapper;

    public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
        if (borrowRecord.getBorrowDate() == null) {
            borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
        }
        borrowRecordMapper.insert(borrowRecord);
        return borrowRecord;
    }
    public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
        return borrowRecordMapper.selectList(
                Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
        );
    }
    public void returnBook(Long recordId) {
        BorrowRecord record = borrowRecordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("未找到借阅记录");
        }
    
        record.setIsReturned(true);
        record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
        borrowRecordMapper.updateById(record);
    }
    public List<BorrowRecord> getBorrowRecords() {
        return borrowRecordMapper.selectList(null);
    }
    
    public BorrowRecord getBorrowRecordById(Long id) {
        return borrowRecordMapper.selectById(id);
    }
    
    public void deleteBorrowRecord(Long id) {
        borrowRecordMapper.deleteById(id);
    }
    
    public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
    
        borrowRecordMapper.updateById(borrowRecord);
        return borrowRecord;
    }
    

    }package com.example.librarysystem.controller; // import com.example.librarysystem.entity.BorrowRecord; import com.example.librarysystem.mapper.BorrowRecordsMapper; import com.example.librarysystem.service.BorrowRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;

    import java.util.HashMap; import java.util.List; import java.util.Map;

    @RestController @RequestMapping("/api/borrow-records") public class BorrowRecordController { @Autowired private BorrowRecordService borrowRecordService; @Autowired private BorrowRecordsMapper borrowRecordsMapper;

    @PostMapping("/borrow")
    public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
        try {
            BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
            return new ResponseEntity<>(savedRecord, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
    @GetMapping("/user/borrow-history/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
        List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
        System.out.println("Borrow history records: " + records);
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @GetMapping()
    public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
        List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @PostMapping("/return/{id}")
    public ResponseEntity<String> returnBook(@PathVariable Long id) {
        try {
            borrowRecordService.returnBook(id);
            return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
        } catch (Exception e) {
            return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/{id}")
    public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
        if (record!= null) {
            return new ResponseEntity<>(record, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
        borrowRecordService.deleteBorrowRecord(id);
        return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
    }
    
    @PostMapping("/edit")
    public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
        BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
        return new ResponseEntity<>(editedRecord, HttpStatus.OK);
    }
    

    } 前端显示数据 63 16 118 2024/12/25 未还 未还 修改代码,让他能够获取数据的正确信息

  8. Assistant

    为了确保前端能够正确显示借阅记录,包括用户名、书名和作者,您需要确保以下几点:

    1. 确保SQL查询正确: 确认后端的 SQL 查询能够正确联结 borrow_records 表、books 表和 users 表,以便能获取到用户名、书名及作者信息。

      在 BorrowRecordsMapper 中的查询:

      @Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " +
              "FROM borrow_records br " +
              "JOIN books b ON br.book_id = b.id " +
              "JOIN users u ON br.user_id = u.id " +
              "WHERE br.user_id = #{userId}")
      List<Map<String, Object>> findBorrowHistoryByUserId(Long userId);
      

      请确保 users 表和 books 表中的数据都与 borrow_records 表中的 user_id 和 book_id 正确关联。

    2. 更新前端显示逻辑: 确保获取的数据中包含用户名、书名和作者,并通过以下步骤在前端代码中正确显示它们。

      在 displayBorrowRecords 函数中,您需要为表格添加正确的数据:

      function displayBorrowRecords(records) {
          const borrowRecordsList = document.getElementById('borrowRecordsList');
          borrowRecordsList.innerHTML = '';
      
          if (records.length === 0) {
              borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
          } else {
              const table = document.createElement('table');
              table.innerHTML = `
                  <tr>
                      <th>用户名</th>
                      <th>书名</th>
                      <th>作者</th>
                      <th>借阅日期</th>
                      <th>还书日期</th>
                      <th>状态</th>
                      <th>操作</th>
                  </tr>
              `;
      
              records.forEach(record => {
                  const borrowDate = new Date(record.borrowDate); // 补充从记录中获取日期
                  const returnDate = record.returnDate ? new Date(record.returnDate) : '未还';
                  const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
                  const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
      
                  const row = document.createElement('tr');
                  row.innerHTML = `
                      <td>${record.username || '未知'}</td>
                      <td>${record.title || '未知'}</td>
                      <td>${record.author || '未知'}</td>
                      <td>${formattedBorrowDate}</td>
                      <td>${formattedReturnDate}</td>
                      <td>${record.isReturned ? '已还' : '未还'}</td>
                      <td style="text-align: center;">
                          <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                      </td>
                  `;
                  table.appendChild(row);
              });
      
              borrowRecordsList.appendChild(table);
          }
      }
      
    3. 确保接口返回正确数据结构: 在调用 loadBorrowRecords 或类似的函数时,应确保返回的数据包含每一条记录的完整信息,包括 username、title 和 author。

    4. 前端测试和调试: 如果上述建议都没有解决问题,请在前端 (loadBorrowRecords() 函数里) 通过 console.log() 打印返回的 records 数据,检查返回的数据结构是否如预期。

      function loadBorrowRecords() {
          fetch('http://localhost:8080/api/borrow-records')
              .then(response => {
                  if (!response.ok) {
                      throw new Error('网络响应不正常');
                  }
                  return response.json();
              })
              .then(records => {
                  console.log(records); // 输出所有记录查看数据结构
                  displayBorrowRecords(records);
              })
              .catch(error => {
                  alert('加载借阅记录时出错:' + error.message);
              });
      }
      

    检查以上各项,应能帮助您获取并正确显示借阅记录的信息。如果依然有问题,建议逐步检查数据库中的数据和后端查询的实现,确保返回数据的完整性。

  9. User

    CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, role ENUM('user', 'admin') NOT NULL );

    CREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100) NOT NULL, author VARCHAR(100) NOT NULL, year_published INT );

    CREATE TABLE borrow_records ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, book_id INT, borrow_date DATE, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (book_id) REFERENCES books(id) ); CREATE TABLE favorites ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, book_id INT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (book_id) REFERENCES books(id) );

    ALTER TABLE books MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE users MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE borrow_records MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE favorites MODIFY COLUMN id INT AUTO_INCREMENT; SELECT * FROM borrow_records;

    ALTER TABLE borrow_records ADD COLUMN return_date DATE; SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC; SELECT id, title, author, year_published FROM books; SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'users' AND REFERENCED_COLUMN_NAME = 'id' AND TABLE_NAME = 'borrow_records';

    				ALTER TABLE borrow_records
    

    DROP FOREIGN KEY borrow_records_ibfk_1;

    ALTER TABLE borrow_records ADD CONSTRAINT borrow_records_user_id_foreign_key FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; SELECT * FROM borrow_records WHERE id = 1; SELECT * FROM borrow_records WHERE user_id = 12; SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'users' AND REFERENCED_COLUMN_NAME = 'id' AND TABLE_NAME = 'favorites';

    			ALTER TABLE favorites
    

    DROP FOREIGN KEY favorites_ibfk_1;

    ALTER TABLE favorites ADD CONSTRAINT favorites_user_id_foreign_key FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; ALTER TABLE borrow_records ADD COLUMN IF NOT EXISTS return_date DATE; ALTER TABLE borrow_records ADD COLUMN returned BOOLEAN DEFAULT FALSE;

    ALTER TABLE borrow_records ADD COLUMN is_returned BOOLEAN DEFAULT FALSE; ADD COLUMN is_returned BOOLEAN DEFAULT FALSE, ALTER TABLE borrow_records ADD COLUMN return_date DATE NULL; 我的请 users 表和 books 表中的数据都与 borrow_records 表中的 user_id 和 book_id 正确关联吗。

  10. Assistant

    为了确认在 borrow_records 表中的 user_id 和 book_id 与 users 表和 books 表的数据是否正确关联,需要执行以下几个步骤:

    1. 检查 users 表中的数据

    你可以通过以下 SQL 查询来查看 users 表中的数据,确保表中有用户,并检查其 id 值:

    SELECT * FROM users;
    

    2. 检查 books 表中的数据

    同样,你可以通过以下 SQL 查询来查看 books 表中的数据,确保表中有书籍,并检查其 id 值:

    SELECT * FROM books;
    

    3. 检查 borrow_records 表中的数据

    执行查询以查看 borrow_records 表,特别是关注 user_id 和 book_id 字段的值。这可以帮助你确认这些值是否存在于 users 和 books 表中:

    SELECT * FROM borrow_records;
    

    4. 验证关联

    此时你已经可以看到三个表的内容。你应该:

    • 确定 borrow_records.user_id 中的每个值都是 users 表中一个有效用户的 id。
    • 确定 borrow_records.book_id 中的每个值都是 books 表中一本有效书籍的 id。

    具体的验证方法

    为了更方便地验证这些关系,您可以编写 JOIN 查询,找出在 borrow_records 表中存在但在 users 或 books 表中不存在的记录。

    查找无效的 user_id

    SELECT br.*
    FROM borrow_records br
    LEFT JOIN users u ON br.user_id = u.id
    WHERE u.id IS NULL;
    

    该查询将返回所有在 borrow_records 表中,但没有在 users 表中找到的 user_id。

    查找无效的 book_id

    SELECT br.*
    FROM borrow_records br
    LEFT JOIN books b ON br.book_id = b.id
    WHERE b.id IS NULL;
    

    该查询将返回所有在 borrow_records 表中,但没有在 books 表中找到的 book_id。

    结论

    • 如果以上两个查询都没有返回任何结果,这表明 borrow_records 表中的 user_id 和 book_id 字段都与相应表的数据正确关联。
    • 如果返回了结果,确保在 users 表和 books 表中存在所有需要的记录,您可能需要删除或更新 borrow_records 表中的无效记录,以确保数据完整性。
  11. User
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: center;
    }
    
    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }
    
    .book-list-container {
        margin-top: 20px;
    }
    
    .book-list-container h2 {
        margin-bottom: 20px;
    }
    
    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }
    
    .book-list-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .book-list-header input[type="checkbox"] {
        margin-right: 10px;
    }
    
    .book-list-container ul {
        list-style-type: none;
        padding: 0;
    }
    
    .book-list-container li {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }
    
    .book-item {
        display: flex;
        align-items: center;
        flex-grow: 1;
    }
    
    .book-actions {
        display: flex;
        align-items: center;
        margin-left: 10px;
    }
    
    .book-actions button {
        margin-left: 18px;
    }
    
    .user-list-container ul {
        list-style-type: none;
        padding: 0;
        width: 100%;
    }
    
    .user-list-container li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        margin-bottom: 10px;
    }
    
    .search-results-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        /* 卡片之间的间隔 */
        margin-top: 20px;
    }
    
    .book-card {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 20px;
        width: 350px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
    }
    
    .book-card:hover {
        transform: scale(1.05);
    }
    
    .book-card h3 {
        margin-top: 0;
    }
    
    .book-card p {
        margin: 5px 0;
    }
    
        </div>
    
    </div>
    <script>
        function logout() {
            alert('已退出登录');
            window.location.href = 'login.html';
        }
        function showForm(type, id = null) {
    
            const formContainer = document.getElementById('formContainer');
            const welcomeMessage = document.getElementById('welcomeMessage');
            formContainer.innerHTML = '';
            formContainer.style.display = 'block';
            welcomeMessage.style.display = 'none';
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>增加图书</h1>
                        <input type="text" placeholder="书名">
                        <input type="text" placeholder="作者">
                        <input type="number" placeholder="出版年份">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
                    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>删除图书</h1>
                        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
                    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>借阅记录</h1>
                        <div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
        <h1 style="text-align: center";>修改图书</h1>
        <input type="text" placeholder="旧书名" id="oldTitle">
        <input type="text" placeholder="新书名" id="newTitle">
        <input type="text" placeholder="新作者" id="newAuthor">
        <input type="number" placeholder="新出版年份" id="newYearPublished">
        <div style="text-align: center;">
        <button style="padding: 10px 20px; font-size: 16px;" onclick="editBookByTitle()">修改</button>
    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>查询图书</h1>
                        <input type="text" placeholder="搜索关键词" id="searchKeyword">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
                    `;
                    break;
                case 'userManagement':
                    loadUsers().then(users => {
                        const userItems = users.map(user => `
            <li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                <div class="book-actions">
                    <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                    <button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </li>`).join("");
    
                        formContainer.innerHTML = `
            <h1 style="text-align: center;">用户管理</h1>
            <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
                <ul style="list-style-type: none; padding: 0;">
                    ${userItems}
                </ul>
            </div>
        `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                    <h2 style="text-align: center";>借阅记录</h2>
                        <!-- 这里可以添加借阅记录的相关表单或内容 -->
                    `;
                    break;
                case 'editUser':
                    fetch(`http://localhost:8080/api/users/edit${id}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch user data');
                            }
                            return response.json();
                        })
                        .then(user => {
                            const formContainer = document.getElementById('formContainer');
                            formContainer.innerHTML = `
                <input type="hidden" value="${id}" name="id">
                <input type="text" placeholder="用户名" value="${user.username}" name="username">
                <input type="password" placeholder="密码" name="password">
                <select name="role">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                </select>
                <button onclick="editUser(${id})">保存</button>
            `;
                        })
                        .catch(error => {
                            console.error('获取用户数据出错:', error);
                            alert('获取用户数据失败: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
                    welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
            }
        }
    
        function deleteBookByTitle() {
            const bookTitle = document.getElementById('bookTitle').value; // 获取书名
            if (!bookTitle) {
                alert('请输入书名以进行删除');
                return;
            }
            fetch('http://localhost:8080/api/books/deleteByTitle', {  // 修改接口路径,对应后端新的删除接口
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ title: bookTitle })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
        function addBook() {
            const formContainer = document.getElementById('formContainer');
            const title = formContainer.querySelector('input[placeholder="书名"]').value;
            const author = formContainer.querySelector('input[placeholder="作者"]').value;
            const yearPublishedInput = formContainer.querySelector('input[placeholder="出版年份"]');
            const year_published_str = yearPublishedInput.value;
    
            let year_published;
            if (year_published_str.trim() === '') {
                alert('请输入出版年份');
                return;
            }
            if (!isNaN(Number(year_published_str))) {
                year_published = parseInt(year_published_str);
            } else {
                alert('出版年份输入格式不正确,请输入合法的数字');
                return;
            }
    
            fetch('http://localhost:8080/api/books/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 确保你有相应的权限
                },
                body: JSON.stringify({ title, author, yearPublished: year_published })
            })
                .then(response => {
                    if (response.ok) {
                        return response.json(); // 响应成功时解析 JSON
                    } else {
                        return response.text().then((text) => {
                            throw new Error(text); // 捕获非 2xx 响应
                        });
                    }
                })
                .then(data => {
                    alert('图书添加成功:' + data.title); // 显示添加成功的书名
                    loadBooks(); // 重新加载书籍
                    formContainer.innerHTML = ''; // 清空表单
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                    alert('添加图书失败:' + error.message); // 提示错误信息
                });
        }
        function searchBooks() {
            const keyword = document.getElementById('searchInput').value;
            if (keyword.trim() === '') {
                alert('请输入搜索关键词');
                return;
            }
    
            fetch('http://localhost:8080/api/books/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: keyword })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    displaySearchResults(data); // 传递返回的数据
                })
                .catch(error => console.error('Error:', error));
        }
    
        function displaySearchResults(books) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = ''; // 清空之前的结果
    
            if (books.length === 0) {
                searchResults.innerHTML = '<p>没有找到相关书籍</p>';
            } else {
                books.forEach(book => {
                    const listItem = document.createElement('div');
                    listItem.className = 'search-result-item';
                    listItem.innerHTML = `
                <div>
                    <strong>书名:</strong> ${book.title}<br>
                    <strong>作者:</strong> ${book.author}<br>
                    <strong>出版年份:</strong> ${book.yearPublished || '未知'}
                </div>
                <div class="book-actions">
                    <button onclick="borrowBook(${book.id})">借阅</button>
                    <button onclick="addToFavorites(${book.id})">添加到收藏</button>
                </div>
            `;
                    searchResults.appendChild(listItem);
                });
            }
        }
    
        function loadBooks() {
            console.log('Starting to load books...');
            return fetch('http://localhost:8080/api/books/all')
                .then(response => {
                    console.log('Received response from get-books:', response);
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log("获取到的图书列表详细信息:", books);
                    displayBooks(books);
                    return Promise.resolve();
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错:' + error.message);
                    return Promise.reject(error);
                });
        }
        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <div class="book-list-header">
                <input type="checkbox" id="selectAllBooks"> 全选
                <button onclick="deleteSelectedBooks()">删除选中</button>
            </div>
            <ul id="bookList">
    `;
            books.forEach(book => {
                let yearToShow = book.year_published;
                // 仅在year_published为null或undefined或为负数时设置为'暂无出版年份'
                if (yearToShow === null || yearToShow === undefined || yearToShow < 0) {
                    yearToShow = '暂无出版年份';
                }
                formContainer.innerHTML += `
    <li style="display: flex; align-items: center;">
        <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;">
            <input type="checkbox" class="bookCheckbox" value="${book.id}">
            <strong>书名:</strong> ${book.title} &nbsp;&nbsp;
            <strong>作者:</strong> ${book.author} &nbsp;&nbsp;
            <strong>出版年份:</strong> ${yearToShow}
        </div>
    <div class="book-actions">
        <button onclick="editBookForm('${book.id}')">编辑</button>
        <button onclick="deleteBook('${book.id}')">删除</button> <!-- 直接调用删除 -->
    </div>
    </li>
    

    ; }); formContainer.innerHTML += `;

            const selectAllCheckbox = document.getElementById('selectAllBooks');
            selectAllCheckbox.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.bookCheckbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
            bookCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }
        function deleteSelectedBooks() {
            const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
            const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);
    
            if (bookIds.length === 0) {
                alert('没有选中任何书籍。');
                return;
            }
    
            if (confirm('确定要删除选中的书籍吗?此操作不可撤销!')) {
                bookIds.forEach(id => {
                    deleteBook(id);
                });
            }
        }
    
    
        function loadUsers() {
            return fetch('http://localhost:8080/api/users/all')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(users => {
                    displayUsers(users);
                    return users;
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    alert('加载用户时出错:' + error.message);
                    // 可以考虑添加重试逻辑,比如延迟一段时间后重试
                    setTimeout(() => {
                        loadUsers();
                    }, 2000);
                    return [];
                });
        }
    
        function displayUsers(users) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">用户管理</h2>
        <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
            <ul style="list-style-type: none; padding: 0;">
                ${users.map(user => `
                    <li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                        <div class="book-actions">
                            <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                            <button onclick="deleteUser('${user.id}', '${user.username}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </div>
    `;
        }
        function loadBorrowRecords() {
    fetch('http://localhost:8080/api/borrow-records')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(records => {
            console.log(records); // 输出所有记录查看数据结构
            displayBorrowRecords(records);
        })
        .catch(error => {
            alert('加载借阅记录时出错:' + error.message);
        });
    

    } function displayBorrowRecords(records) { const borrowRecordsList = document.getElementById('borrowRecordsList'); borrowRecordsList.innerHTML = '';

    if (records.length === 0) {
        borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
    } else {
        const table = document.createElement('table');
        table.innerHTML = `
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>作者</th>
                <th>借阅日期</th>
                <th>还书日期</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        `;
    
        records.forEach(record => {
            const borrowDate = new Date(record.borrowDate); // 补充从记录中获取日期
            const returnDate = record.returnDate ? new Date(record.returnDate) : '未还';
            const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
            const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
    
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.username || '未知'}</td>
                <td>${record.title || '未知'}</td>
                <td>${record.author || '未知'}</td>
                <td>${formattedBorrowDate}</td>
                <td>${formattedReturnDate}</td>
                <td>${record.isReturned ? '已还' : '未还'}</td>
                <td style="text-align: center;">
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
            table.appendChild(row);
        });
    
        borrowRecordsList.appendChild(table);
    }
    

    }

        function deleteUser(id) {
            if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
                fetch(`http://localhost:8080/api/users/${id}`, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' }
                })
                    .then(response => {
                        if (response.status === 200) {
                            return response.text();
                        } else if (response.status === 404) {
                            throw new Error('用户不存在,无法删除');
                        } else {
                            throw new Error('删除用户时出现未知错误,状态码:' + response.status);
                        }
                    })
                    .then(data => {
                        alert('用户删除成功');
                        loadUsers(); // 重新加载用户列表
                    })
                    .catch(error => {
                        console.error('Error deleting user:', error);
                        alert('删除用户时出现错误:' + error.message);
                    });
            }
        }
        function editUserForm(id) {
            fetch(`http://localhost:8080/api/users/${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败,状态码:' + response.status);
                    }
                    return response.json();
                })
                .then(user => {
                    console.log('获取到的用户信息:', user);
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                    <form id="editUserForm">
                        <input type="hidden" value="${id}" name="id">
                        <input type="text" placeholder="用户名" value="${user.username}" name="username">
                        <input type="password" placeholder="旧密码" name="oldPassword" required>
                        <input type="password" placeholder="新密码" name="newPassword">
                        <select name="role">
                            <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                        </select>
                        <button type="button" onclick="editUser(${id})">保存</button>
                        <button type="button" onclick="cancelEditUser()">取消</button>
                    </form>
                `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错:', error);
                    alert('获取用户信息失败,请稍后重试:' + error.message);
                });
        }
        function editUser(id) {
            const form = document.querySelector(`#editUserForm`);
            if (!form || !(form instanceof HTMLFormElement)) {
                return;
            }
            const formData = new FormData(form);
            // 处理可能存在格式问题的数据,比如去除密码字段前后空格
            formData.set('username', formData.get('username').trim());
            formData.set('oldPassword', formData.get('oldPassword').trim());
            formData.set('newPassword', formData.get('newPassword').trim());
            const data = Object.fromEntries(formData.entries());
    
            // 发送POST请求到/api/users/edit
            fetch('http://localhost:8080/api/users/edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        // 处理错误响应
                        return response.json().then(err => {
                            alert('编辑用户失败,原因:' + (err.message || '未知错误'));
                        });
                    }
                    return response.json(); // 假设成功响应也是JSON格式
                })
                .then(data => {
                    // 处理成功响应
                    alert(data.message || '用户信息更新成功');
                    loadUsers(); // 重新加载用户列表
                })
                .catch(error => {
                    console.error('Error editing user:', error);
                    alert('编辑用户信息时出错,请稍后重试:' + error.message);
                });
        }
        function editBookForm(bookId) {
            fetch(`http://localhost:8080/api/books/${bookId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('未能获取图书信息');
                    }
                    return response.json();
                })
                .then(book => {
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                <h2>修改图书</h2>
                <input type="hidden" value="${book.id}" id="bookId">
                <input type="text" placeholder="书名" id="newTitle" value="${book.title}">
                <input type="text" placeholder="作者" id="newAuthor" value="${book.author}">
                <input type="number" placeholder="出版年份" id="newYearPublished" value="${book.yearPublished}">
                <button onclick="editBook()">保存</button>
                <button onclick="cancelEditBook()">取消</button>
            `;
                })
                .catch(error => {
                    alert('获取图书信息失败,请稍后重试:' + error.message);
                });
        }
    
        function deleteBook(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }
            fetch(`http://localhost:8080/api/books/${bookId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 加上相应头,确认请求权限
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错:' + error.message);
                });
        }
    
        function editBook() {
            const bookId = document.getElementById('bookId').value;
            let newTitle = document.getElementById('newTitle').value;
            let newAuthor = document.getElementById('newAuthor').value;
            let newYearPublished = document.getElementById('newYearPublished').value;
    
            if (newTitle === '' || newAuthor === '' || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            const book = {
                id: parseInt(bookId),
                title: newTitle,
                author: newAuthor,
                year_published: parseInt(newYearPublished) // 确保使用合适的字段名称
            };
    
            fetch('http://localhost:8080/api/books/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 请确保权限设置
                },
                body: JSON.stringify(book)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书修改成功');
                    loadBooks(); // 刷新书籍列表
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function editBookByTitle() {
            const oldTitle = document.getElementById('oldTitle').value;
            const newTitle = document.getElementById('newTitle').value;
            const newAuthor = document.getElementById('newAuthor').value;
            const newYearPublished = document.getElementById('newYearPublished').value;
    
            if (!oldTitle || !newTitle || !newAuthor || newYearPublished === '') {
                alert('请填写完整信息');
                return;
            }
    
            fetch('http://localhost:8080/api/books/editByTitle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldTitle: oldTitle,
                    newTitle: newTitle,
                    newAuthor: newAuthor,
                    newYearPublished: newYearPublished
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement');
                })
                .catch(error => {
                    alert('修改图书时出错:' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!`)) {
                deleteBorrowRecord(recordId);
            }
        }
    
        function deleteBorrowRecord(recordId) {
            fetch(`http://localhost:8080/api/borrow-records/${recordId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('借阅记录删除成功');
                    loadBorrowRecords(); // 重新加载借阅记录
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错:' + error.message);
                });
        }
    
        // 获取当前管理员信息
        function fetchCurrentAdmin() {
            fetch('http://localhost:8080/admin/current')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log(data);
    
                    document.getElementById('adminName').textContent = `管理员:${data.username}`;
                })
                .catch(error => {
                    console.error('获取管理员名错误:', error);
                    document.getElementById('adminName').textContent = '管理员:未知'; // 出错时处理
                });
        }
    </script>
    
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.example.librarysystem.entity.Books;
    import com.example.librarysystem.mapper.BooksMapper;
    import com.example.librarysystem.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    
    @RestController
    @RequestMapping("/api/books")
    public class BookController {
        @Autowired
        private BookService bookService;
    
        @Autowired
        private BooksMapper booksMapper;
    
        // 添加图书的接口
        @PostMapping("/add")
        public ResponseEntity<?> addBook(@RequestBody Books book) {
            try {
                // 确保在此处获取有效内容
                if (book.getTitle() == null || book.getTitle().isEmpty()) {
                    return new ResponseEntity<>("书名不能为空", HttpStatus.BAD_REQUEST);
                }
                Books savedBook = bookService.addBook(book);
                return new ResponseEntity<>(savedBook, HttpStatus.OK);
            } catch (Exception e) {
                System.err.println("添加图书时出错: " + e.getMessage()); // 日志错误信息
                return new ResponseEntity<>("添加图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        // 根据书名删除图书的新接口
        @PostMapping("/deleteByTitle")
        public ResponseEntity<?> deleteBookByTitle(@RequestBody Map<String, String> map, @RequestHeader(value = "user-type", required = false) String userType) {
            if (!"admin".equals(userType)) {
    
    
                return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
            }
            String title = map.get("title");
            try {
                bookService.deleteBookByTitle(title);
                return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    
        @DeleteMapping("/{id}")
        public ResponseEntity<?> deleteBook(@PathVariable Long id, @RequestHeader(value = "user-type", required = false) String userType) {
            if (!"admin".equals(userType)) {
                return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
            }
            try {
                bookService.deleteBook(id);
                return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        @GetMapping("/{id}")
        public ResponseEntity<Books> getBookById(@PathVariable Long id) {
            Books book = bookService.getBookById(id);
    
            if (book == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
    
            return new ResponseEntity<>(book, HttpStatus.OK);
        }
        // 新增根据书名修改图书的接口
        @PostMapping("/editByTitle")
        public ResponseEntity<?> editBookByTitle(@RequestBody Map<String, String> map) {
            String oldTitle = map.get("oldTitle");
            String newTitle = map.get("newTitle");
            String newAuthor = map.get("newAuthor");
            String newYearPublishedStr = map.get("newYearPublished");
            int newYearPublished = 0;
            try {
                if (newYearPublishedStr!= null &&!newYearPublishedStr.isEmpty()) {
                    newYearPublished = Integer.parseInt(newYearPublishedStr);
                }
            } catch (NumberFormatException e) {
                return new ResponseEntity<>("出版年份格式错误", HttpStatus.BAD_REQUEST);
            }
            Books newBookInfo = new Books();
            newBookInfo.setTitle(newTitle);
            newBookInfo.setAuthor(newAuthor);
            newBookInfo.setYearPublished(newYearPublished);
            try {
                bookService.editBookByTitle(oldTitle, newBookInfo);
                return new ResponseEntity<>("Book edited successfully", HttpStatus.OK);
            } catch (Exception e) {
                return new ResponseEntity<>("修改图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        @GetMapping("/all")
        public ResponseEntity<List<Books>> getBooks() {
            List<Books> books = bookService.getBooks();
            return new ResponseEntity<>(books, HttpStatus.OK);
        }
    
        @PostMapping("/edit")
        public ResponseEntity<?> editBook(@RequestBody Books book) {
            Books editedBook = bookService.editBook(book);
            return new ResponseEntity<>(editedBook, HttpStatus.OK);
        }
    
        @PostMapping("/search")
        public ResponseEntity<List<Books>> searchBooks(@RequestBody Map<String, String> map) {
            String keyword = map.get("keyword"); // 获取搜索关键字
            System.out.println("Searching for keyword: " + keyword); // 打印接收的关键词
    
            List<Books> booksList = null;
            try {
                if (keyword != null && !keyword.isEmpty()) {
                    booksList = booksMapper.selectList(Wrappers.<Books>lambdaQuery()
                            .like(Books::getTitle, keyword) // 模糊查询书名
                            .or()
                            .like(Books::getAuthor, keyword)); // 或者根据作者模糊查询
                    System.out.println("Total books found: " + booksList.size()); // 打印搜索到的书籍数量
                } else {
                    System.out.println("关键词为空");
                }
            } catch (Exception e) {
                booksList = Collections.emptyList(); // 如果出错,返回空列表
                System.err.println("Error during search: " + e.getMessage());
            }
    
            return new ResponseEntity<>(booksList, HttpStatus.OK);
        }
    }package com.example.librarysystem.controller;
    

    // import com.example.librarysystem.entity.BorrowRecord; import com.example.librarysystem.mapper.BorrowRecordsMapper; import com.example.librarysystem.service.BorrowRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;

    import java.util.HashMap; import java.util.List; import java.util.Map;

    @RestController @RequestMapping("/api/borrow-records") public class BorrowRecordController { @Autowired private BorrowRecordService borrowRecordService; @Autowired private BorrowRecordsMapper borrowRecordsMapper;

    @PostMapping("/borrow")
    public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
        try {
            BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
            return new ResponseEntity<>(savedRecord, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
    @GetMapping("/user/borrow-history/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
        List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
        System.out.println("Borrow history records: " + records);
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @GetMapping()
    public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
        List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
        return new ResponseEntity<>(records, HttpStatus.OK);
    }
    @PostMapping("/return/{id}")
    public ResponseEntity<String> returnBook(@PathVariable Long id) {
        try {
            borrowRecordService.returnBook(id);
            return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
        } catch (Exception e) {
            return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/{id}")
    public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
        if (record!= null) {
            return new ResponseEntity<>(record, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
        borrowRecordService.deleteBorrowRecord(id);
        return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
    }
    
    @PostMapping("/edit")
    public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
        BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
        return new ResponseEntity<>(editedRecord, HttpStatus.OK);
    }
    

    }package com.example.librarysystem.entity;

    import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable;

    import lombok.Getter; import lombok.Setter;

    /**

    • @author xxx
    • @since 2024-12-23 */ @Getter @Setter

    public class Books implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    
    private String title;
    
    private String author;
    
    @TableField(value = "year_published")
    private Integer yearPublished;
    
    public Integer getYear_published(){
        return yearPublished;
    }
    
    
    public void setYear_published(Integer yearPublished){
        this.yearPublished = yearPublished;
    }
    

    } package com.example.librarysystem.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.time.LocalDateTime;

    import lombok.Getter; import lombok.Setter;

    /**

    • @author xxx
    • @since 2024-12-23 */ @Getter @Setter @TableName("borrow_records")

    public class BorrowRecord implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    
    private Integer userId;
    
    private Integer bookId;
    
    private LocalDateTime borrowDate;
    
    private String returnDate;
    
    private Boolean isReturned;
    
    private String status;
    

    } package com.example.librarysystem.mapper;

    import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.librarysystem.entity.BorrowRecord; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select;

    import java.util.List; import java.util.Map;

    /**

    • Mapper 接口

    • @author xxx

    • @since 2024-12-23 */ @Mapper public interface BorrowRecordsMapper extends BaseMapper { @Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " + "FROM borrow_records br " + "JOIN books b ON br.book_id = b.id " + "JOIN users u ON br.user_id = u.id " + "WHERE br.user_id = #{userId}") List<Map<String, Object>> findBorrowHistoryByUserId(Long userId); } package com.example.librarysystem.service;

      import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.example.librarysystem.entity.Books; import com.example.librarysystem.mapper.BooksMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

      import java.util.List;

      @Service public class BookService {

       @Autowired
       private BooksMapper bookMapper;
      
       public Books addBook(Books books) {
           try {
               // 可以添加日志打印出版年份的值,便于排查问题
               System.out.println("准备插入图书的出版年份: " + books.getYearPublished());
               bookMapper.insert(books);
               return books;
           } catch (Exception e) {
               throw new RuntimeException("图书插入数据库失败", e);
           }
       }
      
       public void deleteBook(Long id) {
           int rowsAffected = bookMapper.deleteById(id);
           if (rowsAffected == 0) {
               throw new RuntimeException("删除图书失败,可能该图书不存在或删除操作出现问题");
           }
       }
       public void deleteBookByTitle(String title) {
           Books book = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, title));
           if (book == null) {
               throw new RuntimeException("要删除的图书不存在");
           }
           int rowsAffected = bookMapper.deleteById(book.getId());
           if (rowsAffected == 0) {
               throw new RuntimeException("删除图书失败,可能删除操作出现问题");
           }
       }
       public List<Books> getBooks() {
           List<Books> booksList = bookMapper.selectList(null);
           for (Books book : booksList) {
               // 只在出版年份为 null 时设置默认值为 0,避免覆盖正确的出版年份
               if (book.getYearPublished() == null) {
                   book.setYearPublished(0);
               }
           }
           return booksList;
       }
       public Books getBookById(Long id) {
           return bookMapper.selectById(id);
       }
       public Books editBook(Books books) {
           if (books.getId() == null) {
               throw new RuntimeException("要修改的图书 id 不能为空");
           }
           // 检查图书是否存在
           Books existingBook = bookMapper.selectById(books.getId());
           if (existingBook == null) {
               throw new RuntimeException("要修改的图书不存在");
           }
           bookMapper.updateById(books);
           return books;
       }
       // 新增根据书名修改图书的方法
       public void editBookByTitle(String oldTitle, Books newBookInfo) {
      
           Books existingBook = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, oldTitle));
           if (existingBook == null) {
               throw new RuntimeException("要修改的图书不存在");
           }
           // 将找到的图书的信息更新为新的信息
           existingBook.setTitle(newBookInfo.getTitle());
           existingBook.setAuthor(newBookInfo.getAuthor());
           existingBook.setYearPublished(newBookInfo.getYearPublished());
           bookMapper.updateById(existingBook);
       }
      

      }package com.example.librarysystem.service; // import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.example.librarysystem.entity.BorrowRecord;

    import com.example.librarysystem.mapper.BorrowRecordsMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

    import java.time.LocalDateTime; import java.util.List;

    @Service public class BorrowRecordService { @Autowired private BorrowRecordsMapper borrowRecordMapper;

    public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
        if (borrowRecord.getBorrowDate() == null) {
            borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
        }
        borrowRecordMapper.insert(borrowRecord);
        return borrowRecord;
    }
    public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
        return borrowRecordMapper.selectList(
                Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
        );
    }
    public void returnBook(Long recordId) {
        BorrowRecord record = borrowRecordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("未找到借阅记录");
        }
    
        record.setIsReturned(true);
        record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
        borrowRecordMapper.updateById(record);
    }
    public List<BorrowRecord> getBorrowRecords() {
        return borrowRecordMapper.selectList(null);
    }
    
    public BorrowRecord getBorrowRecordById(Long id) {
        return borrowRecordMapper.selectById(id);
    }
    
    public void deleteBorrowRecord(Long id) {
        borrowRecordMapper.deleteById(id);
    }
    
    public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
    
        borrowRecordMapper.updateById(borrowRecord);
        return borrowRecord;
    }
    

    }package com.example.librarysystem.mapper;

    import com.example.librarysystem.entity.Books; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper;

    /**

    • Mapper 接口
    • @author xxx
    • @since 2024-12-23

    */

    @Mapper public interface BooksMapper extends BaseMapper {

    } CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, role ENUM('user', 'admin') NOT NULL );

    CREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100) NOT NULL, author VARCHAR(100) NOT NULL, year_published INT );

    CREATE TABLE borrow_records ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, book_id INT, borrow_date DATE, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (book_id) REFERENCES books(id) ); CREATE TABLE favorites ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, book_id INT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (book_id) REFERENCES books(id) );

    ALTER TABLE books MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE users MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE borrow_records MODIFY COLUMN id INT AUTO_INCREMENT; ALTER TABLE favorites MODIFY COLUMN id INT AUTO_INCREMENT; SELECT * FROM borrow_records;

    ALTER TABLE borrow_records ADD COLUMN return_date DATE; SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC; SELECT id, title, author, year_published FROM books; SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'users' AND REFERENCED_COLUMN_NAME = 'id' AND TABLE_NAME = 'borrow_records';

    				ALTER TABLE borrow_records
    

    DROP FOREIGN KEY borrow_records_ibfk_1;

    ALTER TABLE borrow_records ADD CONSTRAINT borrow_records_user_id_foreign_key FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; SELECT * FROM borrow_records WHERE id = 1; SELECT * FROM borrow_records WHERE user_id = 12; SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'users' AND REFERENCED_COLUMN_NAME = 'id' AND TABLE_NAME = 'favorites';

    			ALTER TABLE favorites
    

    DROP FOREIGN KEY favorites_ibfk_1;

    ALTER TABLE favorites ADD CONSTRAINT favorites_user_id_foreign_key FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; ALTER TABLE borrow_records ADD COLUMN IF NOT EXISTS return_date DATE; ALTER TABLE borrow_records ADD COLUMN returned BOOLEAN DEFAULT FALSE;

    ALTER TABLE borrow_records ADD COLUMN is_returned BOOLEAN DEFAULT FALSE; ADD COLUMN is_returned BOOLEAN DEFAULT FALSE, ALTER TABLE borrow_records ADD COLUMN return_date DATE NULL;

    前端还是不能显示正确数据 未知 未知 未知 2024/12/25 未还 未还

  12. Assistant

    根据你提供的代码和数据库结构,出现的问题是前端页面无法正确显示借阅记录中的用户、书名和作者信息,而显示为 未知。此问题一般涉及到数据库联结、后端数据处理、以及前端数据显示几个层面。下面,我将对可能存在问题的地方进行分析,并提供一些解决方案。

    1. 数据库结构和外键关系

    你提供了数据库表结构,其中 borrow_records 表通过外键 (foreign key) 关联到 users 表和 books 表。这些外键确保了 user_id 和 book_id 正确指向各自表中的有效记录。

    请确保在 borrow_records 表中,所有的 user_id 和 book_id 都对应到 users 表的 id 和 books 表的 id。你可以使用以下 SQL 查询来确认:

    检查 users 表

    SELECT * FROM users;
    

    检查 books 表

    SELECT * FROM books;
    

    检查 borrow_records 表

    SELECT * FROM borrow_records;
    

    检查无效的 user_id

    使用这个查询找出在 borrow_records 中存在但在 users 中不存在的 user_id:

    SELECT br.*
    FROM borrow_records br
    LEFT JOIN users u ON br.user_id = u.id
    WHERE u.id IS NULL;
    

    检查无效的 book_id

    使用这个查询找出在 borrow_records 中存在但在 books 中不存在的 book_id:

    SELECT br.*
    FROM borrow_records br
    LEFT JOIN books b ON br.book_id = b.id
    WHERE b.id IS NULL;
    

    2. 后端数据处理

    在你的 BorrowRecordsMapper 中,获取借阅记录时使用的 SQL 查询应该能正确联结用户和书籍信息。请确保你的 SQL 语句如下所示:

    @Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " +
            "FROM borrow_records br " +
            "JOIN books b ON br.book_id = b.id " +
            "JOIN users u ON br.user_id = u.id " +
            "WHERE br.user_id = #{userId}")
    List<Map<String, Object>> findBorrowHistoryByUserId(Long userId);
    

    此查询中使用 JOIN 语句将借阅记录、用户和书籍表连接在一起。确保这段代码在接收到请求时能正确执行。

    3. 前端处理和数据显示

    在前端展示借阅记录的 displayBorrowRecords 函数中,请确保字符串拼接中使用了正确字段。你的函数应该像这样:

    function displayBorrowRecords(records) {
        const borrowRecordsList = document.getElementById('borrowRecordsList');
        borrowRecordsList.innerHTML = '';
    
        if (records.length === 0) {
            borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
        } else {
            const table = document.createElement('table');
            table.innerHTML = `
                <tr>
                    <th>用户名</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>借阅日期</th>
                    <th>还书日期</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            `;
    
            records.forEach(record => {
                const borrowDate = new Date(record.borrow_date);
                const returnDate = record.return_date ? new Date(record.return_date) : '未还';
                const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN');
                const formattedReturnDate = returnDate instanceof Date ? returnDate.toLocaleDateString('zh-CN') : '未还';
    
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${record.username || '未知'}</td>
                    <td>${record.title || '未知'}</td>
                    <td>${record.author || '未知'}</td>
                    <td>${formattedBorrowDate}</td>
                    <td>${formattedReturnDate}</td>
                    <td>${record.is_returned ? '已还' : '未还'}</td>
                    <td style="text-align: center;">
                        <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                    </td>
                `;
                table.appendChild(row);
            });
    
            borrowRecordsList.appendChild(table);
        }
    }
    

    4. 测试和调试

    1. 打印 logs:在前端捕获 records 后使用 console.log(records);,以检查从后端返回的记录数据结构,确认用户名、书名和作者字段是否存在。

    2. 检查返回数据:在后端的 BorrowRecordController 中,检查使用 findBorrowHistoryByUserId 方法返回的数据,并在控制台中输出。

    例如,在 getBorrowHistoryByUserId 方法中添加:

    System.out.println("Borrow history records: " + records);
    
    1. 处理响应数据:确保前端在 loadBorrowRecords 函数获取数据后将其以预期的方式展示。

    总结

    通过以上步骤,你应该能够定位和解决前端页面无法正确显示借阅记录的问题。确保数据的每一个环节都能顺畅:从数据库结构到后端业务逻辑,再到前端的数据处理和展示。如果仍有问题,可以进一步逐步排查。