团队冲刺第三天

昨天:
完善了完善查询功能
支持按书名、类型、借阅状态等多条件检索,优化搜索性能(如模糊查询)。
考虑加入排序功能(如按ID或书名排序)。
扩展管理员模块
实现管理员登录验证(如基于密码或指纹)。
开发借阅记录管理界面,显示历史操作日志。
今天:实现了用户的图书查询,自助借助功能
代码:BookRepository接口
public interface BookRepository extends JpaRepository<Book, Long> {

// 基本查询方法
List<Book> findByTitleContaining(String title);
List<Book> findByAuthorContaining(String author);
List<Book> findByIsbn(String isbn);
List<Book> findByCategory(String category);

// 复杂查询
@Query("SELECT b FROM Book b WHERE " +
       "(:title IS NULL OR b.title LIKE %:title%) AND " +
       "(:author IS NULL OR b.author LIKE %:author%) AND " +
       "(:category IS NULL OR b.category = :category) AND " +
       "b.availableCopies > 0")
Page<Book> searchBooks(@Param("title") String title,
                      @Param("author") String author,
                      @Param("category") String category,
                      Pageable pageable);

}
BookService实现
@Service
public class BookService {

@Autowired
private BookRepository bookRepository;

public Page<Book> searchBooks(String title, String author, String category, int page, int size) {
    Pageable pageable = PageRequest.of(page, size, Sort.by("title").ascending());
    return bookRepository.searchBooks(title, author, category, pageable);
}

public Book getBookDetails(Long id) {
    return bookRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Book not found"));
}

}

用java开发web程序针对图书这个东西来说要怎么实现图书查询,自助借助功能呢?springboot

使用Spring Boot实现图书查询和自助借阅功能
下面我将详细介绍如何使用Spring Boot框架实现图书管理系统中的查询和自助借阅功能。

  1. 系统架构设计
    技术栈选择
    后端: Spring Boot 2.x
    数据库: MySQL/PostgreSQL
    ORM: Spring Data JPA (或MyBatis)
    安全框架: Spring Security
    前端: Thymeleaf (或前后端分离架构)
  2. 数据库设计
    主要表结构
    SQL
    CREATE TABLE book (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    isbn VARCHAR(20) UNIQUE NOT NULL,
    title VARCHAR(100) NOT NULL,
    author VARCHAR(50) NOT NULL,
    publisher VARCHAR(50),
    publish_date DATE,
    category VARCHAR(30),
    total_copies INT DEFAULT 1,
    available_copies INT DEFAULT 1,
    location VARCHAR(50),
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );

CREATE TABLE user (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
real_name VARCHAR(30),
email VARCHAR(50) UNIQUE,
phone VARCHAR(20),
role ENUM('ADMIN', 'LIBRARIAN', 'MEMBER') DEFAULT 'MEMBER',
status TINYINT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE borrow_record (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL,
book_id BIGINT NOT NULL,
borrow_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
due_date TIMESTAMP,
return_date TIMESTAMP,
status ENUM('BORROWED', 'RETURNED', 'OVERDUE') DEFAULT 'BORROWED',
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (book_id) REFERENCES book(id)
);
3. 实现图书查询功能
Book实体类
Java
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String isbn;

@Column(nullable = false)
private String title;

@Column(nullable = false)
private String author;

private String publisher;
private Date publishDate;
private String category;

@Column(columnDefinition = "integer default 1")
private Integer totalCopies;

@Column(columnDefinition = "integer default 1")
private Integer availableCopies;

private String location;
private String description;

@CreationTimestamp
private Timestamp createdAt;

// Getters and Setters

}
BookRepository接口
Java
public interface BookRepository extends JpaRepository<Book, Long> {

// 基本查询方法
List<Book> findByTitleContaining(String title);
List<Book> findByAuthorContaining(String author);
List<Book> findByIsbn(String isbn);
List<Book> findByCategory(String category);

// 复杂查询
@Query("SELECT b FROM Book b WHERE " +
       "(:title IS NULL OR b.title LIKE %:title%) AND " +
       "(:author IS NULL OR b.author LIKE %:author%) AND " +
       "(:category IS NULL OR b.category = :category) AND " +
       "b.availableCopies > 0")
Page<Book> searchBooks(@Param("title") String title,
                      @Param("author") String author,
                      @Param("category") String category,
                      Pageable pageable);

}
BookService实现
Java
@Service
public class BookService {

@Autowired
private BookRepository bookRepository;

public Page<Book> searchBooks(String title, String author, String category, int page, int size) {
    Pageable pageable = PageRequest.of(page, size, Sort.by("title").ascending());
    return bookRepository.searchBooks(title, author, category, pageable);
}

public Book getBookDetails(Long id) {
    return bookRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Book not found"));
}

}
BookController层
@Controller
@RequestMapping("/books")
public class BookController {

@Autowired
private BookService bookService;

@GetMapping
public String listBooks(
        @RequestParam(required = false) String title,
        @RequestParam(required = false) String author,
        @RequestParam(required = false) String category,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size,
        Model model) {
    
    Page<Book> bookPage = bookService.searchBooks(title, author, category, page, size);
    model.addAttribute("books", bookPage);
    model.addAttribute("title", title);
    model.addAttribute("author", author);
    model.addAttribute("category", category);
    
    return "book/list";
}

@GetMapping("/{id}")
public String viewBook(@PathVariable Long id, Model model) {
    Book book = bookService.getBookDetails(id);
    model.addAttribute("book", book);
    return "book/view";
}

}
遇到的问题:当多个用户同时尝试借阅同一本图书时,可能会出现"超借"现象,即图书的可用数量变为负数。方案1: 数据库悲观锁
Java
@Transactional
public BorrowRecord borrowBook(Long bookId, Long userId) {
// 使用悲观锁锁定图书记录
Book book = bookRepository.findByIdWithLock(bookId)
.orElseThrow(() -> new ResourceNotFoundException("Book not found"));
}

// 在BookRepository中添加
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT b FROM Book b WHERE b.id = :id")
Optional findByIdWithLock(@Param("id") Long id);
当图书数量庞大(如超过10万册)时,复杂的多条件查询(特别是模糊查询)可能导致性能下降,响应时间变长。
添加适当的数据库索引
明天:实现自主借阅,查询借阅功能

posted @ 2025-04-19 22:08  马瑞鑫03  阅读(40)  评论(0)    收藏  举报