@Getter
@Setter
@TableName("favorites") // 指定对应的数据库表名
public class Favorite implements Serializable {
private static final long serialVersionUID = 1L;
code
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long userId; // 注意这里也要保持数据类型与数据库一致,若user_id为Long则在此设置为Long
private Long bookId; // 注意这里也要保持数据类型与数据库一致,若book_id为Long则在此设置为Long
} package com.example.librarysystem.service;
code
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.librarysystem.dto.FavoriteDTO;
import com.example.librarysystem.entity.Books;
import com.example.librarysystem.entity.Favorite;
import com.example.librarysystem.mapper.BooksMapper; // 导入 BooksMapper
import com.example.librarysystem.mapper.FavoritesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class FavoriteService {
@Autowired
private FavoritesMapper favoriteMapper;
@Autowired
private BooksMapper booksMapper; // 添加 BooksMapper
public Favorite addFavorite(Favorite favorite) {
favoriteMapper.insert(favorite); // 使用 BaseMapper 提供的 insert 方法
return favorite;
}
public void removeFavorite(Long userId, Long bookId) {
favoriteMapper.delete(
Wrappers.<Favorite>lambdaQuery().eq(Favorite::getUserId, userId).eq(Favorite::getBookId, bookId)
);
}
public void deleteFavorite(Long id) {
favoriteMapper.deleteById(id);
}
public List<FavoriteDTO> getFavoritesByUserId(Long userId) {
List<Favorite> favorites = favoriteMapper.selectList(
Wrappers.<Favorite>lambdaQuery().eq(Favorite::getUserId, userId)
);
List<FavoriteDTO> favoriteDTOs = new ArrayList<>();
for (Favorite favorite : favorites) {
Books book = booksMapper.selectById(favorite.getBookId()); // 获取书籍信息
FavoriteDTO dto = new FavoriteDTO();
dto.setId(favorite.getId());
dto.setUserId(favorite.getUserId());
dto.setBookId(favorite.getBookId());
dto.setBookTitle(book != null ? book.getTitle() : "未知"); // 书名
dto.setBookAuthor(book != null ? book.getAuthor() : "未知"); // 作者
favoriteDTOs.add(dto);
}
return favoriteDTOs;
}
} 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.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);
}
}修改代码,当我的借阅记录有记录时,我搜索书籍显示书籍后,点击借阅记录他就会报错user.html:377
Error: TypeError: Cannot read properties of undefined (reading 'ok')
at user.html:367:27
(匿名) @ user.html:377
@PostMapping("/borrow")
public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
try {
// 确保借阅记录必须有用户ID和书籍ID
if (borrowRecord.getUserId() == null || borrowRecord.getBookId() == null) {
return new ResponseEntity<>("用户 ID 和 书籍 ID 不能为空", HttpStatus.BAD_REQUEST);
}
// 添加借阅日期,如果没有指定
if (borrowRecord.getBorrowDate() == null) {
borrowRecord.setBorrowDate(LocalDateTime.now());
}
// 保存借阅记录
BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
return new ResponseEntity<>(savedRecord, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
3. 后端 - 确保借阅检查机制
实现一个方法来检查用户是否已经借阅书籍,如果有,返回特定的响应。
java
@GetMapping("/user/hasBorrowed/{userId}")
public ResponseEntity<Boolean> hasBorrowed(@PathVariable Long userId) {
List<BorrowRecord> records = borrowRecordService.getBorrowRecordsByUserId(userId);
return new ResponseEntity<>(!records.isEmpty(), HttpStatus.OK);
}
@GetMapping("/user/borrow-history/{userId}")
public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
return new ResponseEntity<>(records, HttpStatus.OK);
}
确保删除借阅记录的 API 设置正确并且称呼了适当的后端逻辑。这里需要核实 API 路径是否正确以及 HTTP 方法是否匹配。
后端确认:
请确认你的删除方法是否正确处理:
java
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
borrowRecordService.deleteBorrowRecord(id);
return new ResponseEntity<>("借阅记录删除成功", HttpStatus.OK);
}