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

ops/2024/12/29 3:39:01/

基于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 {@Autowiredprivate 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 {@Autowiredprivate 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 {@Autowiredprivate BookService bookService;@GetMappingpublic 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";}@PostMappingpublic 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 {@Autowiredprivate ReaderService readerService;@GetMappingpublic 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";}@PostMappingpublic 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 configurationPUBLIC "-//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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://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/javaeehttp://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.ppmy.cn/ops/145816.html

相关文章

Jo-im开发:用于WebRTC的ICE中继服务器Coturn搭建

前言 本人计划开发一套具备文本、语音、视频通话功能的IM demo&#xff0c;同时具备多人在线会议功能&#xff0c;按习惯大概会开源版定义名称为Duihao jo-im&#xff0c;本案主要用于实现语音视频通话的基础组件支撑。因为我们选择基于WebRTC实现IM中语音、视频通话&#xff…

基于特征工程(pca分析)、小波去噪以及数据增强,同时采用基于注意力机制的BiLSTM、随机森林、ARIMA模型进行序列数据预测

本文采用特征工程&#xff08;pca分析&#xff09;、小波去噪以及数据增强&#xff0c;同时采用基于注意力机制的BiLSTM、随机森林、ARIMA模型进行序列数据预测 基于BILSTM&#xff08;双向长短期记忆网络&#xff09;、随机森林回归和ARIMA&#xff08;自回归积分滑动平均&am…

对外发PDF设置打开次数

在线 Host PDF 文件并对链接进行限制——保障文件安全的最佳解决方案 在数字化办公和远程协作日益普及的今天&#xff0c;如何安全高效地分享 PDF 文件成为许多用户关注的重点。MaiPDF 作为一款功能强大的在线工具&#xff0c;不仅支持在线 host PDF 文件&#xff0c;还提供多…

c++编译过程初识

编译过程 预处理&#xff1a;主要是执行一些预处理指令&#xff0c;主要是#开头的代码&#xff0c;如#include 的头文件、#define 定义的宏常量、#ifdef #ifndef #endif等条件编译的代码&#xff0c;具体包括查找头文件、进行宏替换、根据条件编译等操作。 g -E example.cpp -…

leetcode hot 100 二叉搜索

35. 搜索插入位置 已解答 简单 相关标签 相关企业 给定一个排序数组和一个目标值&#xff0c;在数组中找到目标值&#xff0c;并返回其索引。如果目标值不存在于数组中&#xff0c;返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 class Solut…

linux——vi命令常用操作

一、vi模式 vi一般分为三种模式&#xff0c;分别是命令行模式、插入模式、末行模式 1.命令模式&#xff1a;控制屏幕光标的移动&#xff0c;按 &#xff1a;进入末行模式&#xff0c;按 i&#xff08;其他插入命令也可&#xff09; 进入插入模式&#xff1b; 2.插入模式&…

node-js Express防盗链

什么是防盗连 一个简单的说明&#xff0c;假如在前端img标签想要引用图片网站上的图片&#xff0c;当你将图片地址放到img标签上想要显示的时候你发现&#xff0c;图片显示不了&#xff0c;这说明网站采用了防盗链。 怎么实现的呢 在请求头中一般会有 Referer&#xff0c;它…

Oracle 备份与恢复 (Docker部署版)

Oracle 备份与恢复 &#xff08;Docker部署版&#xff09; 一&#xff0c;宿主机设置定时备份脚本 1.检查Oracle容器是否正常运行 docker ps2.进入容器&#xff0c;创建shell脚本 #oracle11g 是容器名 docker exec -it oracle11g bash #创建数据库dump的目录 mkdir -p /hom…