当前位置: 首页 > article >正文

基于SSM(Spring + Spring MVC + MyBatis)框架构建一个图书馆仓储管理系统

基于SSM(Spring + Spring MVC + MyBatis)框架构建一个图书馆仓储管理系统是一个涉及多个功能模块的项目,包括但不限于图书管理、读者管理、借阅管理、归还管理等。

1. 环境准备

确保你已经安装了以下工具和环境:

  • Java Development Kit (JDK)
  • 集成开发环境 (IDE):如Eclipse, IntelliJ IDEA
  • 数据库:如MySQL, PostgreSQL
  • 构建工具:如Maven或Gradle
  • 服务器:如Apache Tomcat

2. 项目结构

创建一个新的Maven项目,并设置好目录结构。通常的Maven项目结构如下:

library-management-system
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example.lms
│   │   ├── resources
│   │   │   ├── mappers
│   │   │   ├── application.properties
│   │   │   └── mybatis-config.xml
│   │   └── webapp
│   │       ├── WEB-INF
│   │       │   ├── views
│   │       │   ├── web.xml
│   │       │   └── spring-servlet.xml
│   │       └── index.jsp
│   └── test
│       └── java
│           └── com.example.lms
└── pom.xml

3. Maven依赖配置 (pom.xml)

pom.xml中添加必要的依赖项:

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.22</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.22</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.22</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.10</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>

    <!-- Servlet API -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- JSP, JSTL -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

4. 数据库设计

设计几个基本的表来支持图书馆的主要功能:

  • books:存储书籍信息。
  • readers:存储读者信息。
  • borrow_records:记录借阅信息。
  • return_records:记录归还信息。

示例SQL语句:

CREATE TABLE books (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    author VARCHAR(255),
    isbn VARCHAR(13) UNIQUE,
    publisher VARCHAR(255),
    publish_date DATE,
    category VARCHAR(100),
    available_copies INT DEFAULT 0
);

CREATE TABLE readers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    gender ENUM('M', 'F') NOT NULL,
    birth_date DATE,
    phone_number VARCHAR(20),
    address TEXT
);

CREATE TABLE borrow_records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    reader_id INT NOT NULL,
    book_id INT NOT NULL,
    borrow_date DATE NOT NULL,
    due_date DATE NOT NULL,
    FOREIGN KEY (reader_id) REFERENCES readers(id),
    FOREIGN KEY (book_id) REFERENCES books(id)
);

CREATE TABLE return_records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    borrow_record_id INT NOT NULL,
    return_date DATE NOT NULL,
    FOREIGN KEY (borrow_record_id) REFERENCES borrow_records(id)
);

5. DAO层 (MyBatis Mapper)

为每个实体创建对应的Mapper接口和XML映射文件。

BookMapper.java:

package com.example.lms.dao;

import com.example.lms.model.Book;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface BookMapper {
    @Select("SELECT * FROM books WHERE id = #{id}")
    Book selectById(Integer id);

    @Insert("INSERT INTO books(title, author, isbn, publisher, publish_date, category, available_copies) VALUES(#{title}, #{author}, #{isbn}, #{publisher}, #{publishDate}, #{category}, #{availableCopies})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Book book);

    @Update("UPDATE books SET title=#{title}, author=#{author}, isbn=#{isbn}, publisher=#{publisher}, publish_date=#{publishDate}, category=#{category}, available_copies=#{availableCopies} WHERE id=#{id}")
    void update(Book book);

    @Delete("DELETE FROM books WHERE id=#{id}")
    void deleteById(Integer id);

    @Select("SELECT * FROM books")
    List<Book> selectAll();
}

ReaderMapper.java:

package com.example.lms.dao;

import com.example.lms.model.Reader;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ReaderMapper {
    @Select("SELECT * FROM readers WHERE id = #{id}")
    Reader selectById(Integer id);

    @Insert("INSERT INTO readers(name, gender, birth_date, phone_number, address) VALUES(#{name}, #{gender}, #{birthDate}, #{phoneNumber}, #{address})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Reader reader);

    @Update("UPDATE readers SET name=#{name}, gender=#{gender}, birth_date=#{birthDate}, phone_number=#{phoneNumber}, address=#{address} WHERE id=#{id}")
    void update(Reader reader);

    @Delete("DELETE FROM readers WHERE id=#{id}")
    void deleteById(Integer id);

    @Select("SELECT * FROM readers")
    List<Reader> selectAll();
}

6. Service层

BookService.java:

package com.example.lms.service;

import com.example.lms.dao.BookMapper;
import com.example.lms.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    public Book getBookById(Integer id) {
        return bookMapper.selectById(id);
    }

    public List<Book> getAllBooks() {
        return bookMapper.selectAll();
    }

    public void addBook(Book book) {
        bookMapper.insert(book);
    }

    public void updateBook(Book book) {
        bookMapper.update(book);
    }

    public void deleteBook(Integer id) {
        bookMapper.deleteById(id);
    }
}

ReaderService.java:

package com.example.lms.service;

import com.example.lms.dao.ReaderMapper;
import com.example.lms.model.Reader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ReaderService {

    @Autowired
    private ReaderMapper readerMapper;

    public Reader getReaderById(Integer id) {
        return readerMapper.selectById(id);
    }

    public List<Reader> getAllReaders() {
        return readerMapper.selectAll();
    }

    public void addReader(Reader reader) {
        readerMapper.insert(reader);
    }

    public void updateReader(Reader reader) {
        readerMapper.update(reader);
    }

    public void deleteReader(Integer id) {
        readerMapper.deleteById(id);
    }
}

7. Controller层

BookController.java:

package com.example.lms.controller;

import com.example.lms.model.Book;
import com.example.lms.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private BookService bookService;

    @GetMapping
    public String listBooks(Model model) {
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "bookList";
    }

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

    @PostMapping
    public String addBook(@ModelAttribute Book book) {
        bookService.addBook(book);
        return "redirect:/books";
    }

    @PutMapping("/{id}")
    public String updateBook(@PathVariable Integer id, @ModelAttribute Book book) {
        book.setId(id);
        bookService.updateBook(book);
        return "redirect:/books/" + id;
    }

    @DeleteMapping("/{id}")
    public String deleteBook(@PathVariable Integer id) {
        bookService.deleteBook(id);
        return "redirect:/books";
    }
}

ReaderController.java:

package com.example.lms.controller;

import com.example.lms.model.Reader;
import com.example.lms.service.ReaderService;
import org.springframework.beans.factory.annotation@Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/readers")
public class ReaderController {

    @Autowired
    private ReaderService readerService;

    @GetMapping
    public String listReaders(Model model) {
        List<Reader> readers = readerService.getAllReaders();
        model.addAttribute("readers", readers);
        return "readerList";
    }

    @GetMapping("/{id}")
    public String viewReader(@PathVariable Integer id, Model model) {
        Reader reader = readerService.getReaderById(id);
        model.addAttribute("reader", reader);
        return "readerView";
    }

    @PostMapping
    public String addReader(@ModelAttribute Reader reader) {
        readerService.addReader(reader);
        return "redirect:/readers";
    }

    @PutMapping("/{id}")
    public String updateReader(@PathVariable Integer id, @ModelAttribute Reader reader) {
        reader.setId(id);
        readerService.updateReader(reader);
        return "redirect:/readers/" + id;
    }

    @DeleteMapping("/{id}")
    public String deleteReader(@PathVariable Integer id) {
        readerService.deleteReader(id);
        return "redirect:/readers";
    }
}

8. 配置文件

application.properties:

# Database connection settings
spring.datasource.url=jdbc:mysql://localhost:3306/library_management?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis configuration
mybatis.mapper-locations=classpath:mappers/*.xml
mybatis.type-aliases-package=com.example.lms.model

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="false"/>
    </settings>
</configuration>

spring-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Component scanning for autowiring and detecting beans -->
    <context:component-scan base-package="com.example.lms" />

    <!-- Data source configuration -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${spring.datasource.driver-class-name}" />
        <property name="url" value="${spring.datasource.url}" />
        <property name="username" value="${spring.datasource.username}" />
        <property name="password" value="${spring.datasource.password}" />
    </bean>

    <!-- Transaction manager for handling transactions -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Enable annotation-driven transaction management -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- MyBatis SqlSessionFactoryBean configuration -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath*:mappers/*.xml" />
    </bean>

    <!-- MyBatis mapper scanner configuration -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.lms.dao" />
    </bean>

    <!-- View resolver for JSP -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>Library Management System</display-name>

    <!-- Front controller for Spring MVC -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Character encoding filter -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

9. 视图层 (JSP)

为书籍和读者列表创建简单的JSP页面。

bookList.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Author</th>
        <th>ISBN</th>
        <th>Publisher</th>
        <th>Publish Date</th>
        <th>Category</th>
        <th>Available Copies</th>
        <th>Actions</th>
    </tr>
    <c:forEach var="book" items="${books}">
        <tr>
            <td>${book.id}</td>
            <td>${book.title}</td>
            <td>${book.author}</td>
            <td>${book.isbn}</td>
            <td>${book.publisher}</td>
            <td>${book.publishDate}</td>
            <td>${book.category}</td>
            <td>${book.availableCopies}</td>
            <td>
                <a href="/books/${book.id}">View</a>
                <a href="/books/${book.id}/edit">Edit</a>
                <a href="/books/${book.id}/delete" οnclick="return confirm('Are you sure you want to delete this book?')">Delete</a>
            </td>
        </tr>
    </c:forEach>
</table>
<a href="/books/new">Add New Book</a>
</body>
</html>

readerList.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Reader List</title>
</head>
<body>
<h1>Reader List</h1>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Birth Date</th>
        <th>Phone Number</th>
        <th>Address</th>
        <th>Actions</th>
    </tr>
    <c:forEach var="reader" items="${readers}">
        <tr>
            <td>${reader.id}</td>
            <td>${reader.name}</td>
            <td>${reader.gender}</td>
            <td>${reader.birthDate}</td>
            <td>${reader.phoneNumber}</td>
            <td>${reader.address}</td>
            <td>
                <a href="/readers/${reader.id}">View</a>
                <a href="/readers/${reader.id}/edit">Edit</a>
                <a href="/readers/${reader.id}/delete" οnclick="return confirm('Are you sure you want to delete this reader?')">Delete</a>
            </td>
        </tr>
    </c:forEach>
</table>
<a href="/readers/new">Add New Reader</a>
</body>
</html>

10. 启动项目

确保你的数据库已经启动,并且根据application.properties中的配置正确设置了数据源连接信息。将项目部署到Tomcat服务器上,启动服务器并访问应用。

11. 扩展功能

为了使系统更加完整和实用,你可以考虑添加以下功能:

  • 用户认证和权限控制:使用Spring Security来保护系统资源。
  • 日志记录:使用Log4j或SLF4J进行日志记录。
  • 搜索功能:允许用户通过关键字搜索书籍或读者。
  • 统计报表:生成借阅情况的统计报表。
  • 邮件通知:当书籍到期时,向读者发送提醒邮件。

http://www.kler.cn/a/455836.html

相关文章:

  • --spring.profiles.active=prod
  • Git如何添加子仓库
  • 深入解析MVCC中Undo Log版本底层存储读取逻辑
  • 基于Debian的Linux发行版的包管理工具
  • 设计一个监控摄像头物联网IOT(webRTC、音视频、文件存储)
  • MetaRename for Mac,适用于 Mac 的文件批量重命名工具
  • 力扣6. Z 字形变换
  • 低代码开源项目Joget的研究——基本概念和Joget7社区版应用
  • Bert中文文本分类
  • 使用 AOP 在 Spring Boot 中实现跟踪和日志记录
  • ES7+ React/Redux/GraphQL/React-Native snippets 使用指南
  • kotlin 函数作为参数
  • Web身份认证 --- Session和JWT Token
  • Python爬虫:爱奇艺榜单数据的实时监控
  • No.1免费开源ERP:Odoo自定义字段添加到配置页中的技术分享
  • 华为仓颉编程语言的应用案例分析
  • 深入解析MVCC中Undo Log版本底层存储读取逻辑
  • [实战]Spring Boot启动卡在Root WebApplicationContext initialization completed in
  • rust windwos 两个edit框
  • 矩阵线性方程组
  • js版本之ES6特性简述【Proxy、Reflect、Iterator、Generator】(五)
  • React vite + less
  • 云原生架构中的中间件容器化:优劣势与实践探索
  • PHP技术全栈开发秘籍:从基础到实战的进阶之旅
  • 深度学习驱动的油气开发技术与应用
  • .NET平台用C#通过字节流动态操作Excel文件