Spring Boot 是一个基于 Java 的快速构建框架,能够简化开发过程,提升开发效率。本文将介绍如何使用 Spring Boot 实现电子书的增删改查(CRUD)功能,并展示一个简单的前端界面以展示电子书的信息。
1. 环境准备
首先,你需要确保你的开发环境中已安装 JDK 和 Maven。接下来,可以通过 Spring Initializr 创建一个新的 Spring Boot 项目,选择以下依赖: - Spring Web - Spring Data JPA - H2 Database (用于内存数据库)
2. 项目结构
创建完项目后,项目结构大致如下:
src
└── main
├── java
│ └── com
│ └── example
│ └── ebook
│ ├── controller
│ ├── entity
│ ├── repository
│ └── service
└── resources
└── application.properties
3. 实体类
创建 Book
实体类,用于映射电子书的信息。
package com.example.ebook.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private String description;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
4. Repository
创建 BookRepository
接口,用于数据库操作。
package com.example.ebook.repository;
import com.example.ebook.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
5. Service
创建业务逻辑层 BookService
。
package com.example.ebook.service;
import com.example.ebook.entity.Book;
import com.example.ebook.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> findAll() {
return bookRepository.findAll();
}
public Book save(Book book) {
return bookRepository.save(book);
}
public void deleteById(Long id) {
bookRepository.deleteById(id);
}
public Book findById(Long id) {
return bookRepository.findById(id).orElse(null);
}
}
6. Controller
创建控制器 BookController
,提供 RESTful API。
package com.example.ebook.controller;
import com.example.ebook.entity.Book;
import com.example.ebook.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public List<Book> getAllBooks() {
return bookService.findAll();
}
@PostMapping
public Book createBook(@RequestBody Book book) {
return bookService.save(book);
}
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
Book book = bookService.findById(id);
return ResponseEntity.ok(book);
}
@PutMapping("/{id}")
public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
Book book = bookService.findById(id);
if (book != null) {
book.setTitle(bookDetails.getTitle());
book.setAuthor(bookDetails.getAuthor());
book.setDescription(bookDetails.getDescription());
bookService.save(book);
return ResponseEntity.ok(book);
}
return ResponseEntity.notFound().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
bookService.deleteById(id);
return ResponseEntity.noContent().build();
}
}
7. 前端界面
为了展示电子书的列表,可以使用简单的 HTML 和 JavaScript:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>电子书列表</title>
<script>
async function fetchBooks() {
const response = await fetch('/api/books');
const books = await response.json();
const bookList = document.getElementById('book-list');
bookList.innerHTML = '';
books.forEach(book => {
const li = document.createElement('li');
li.textContent = `${book.title} - ${book.author}`;
bookList.appendChild(li);
});
}
window.onload = fetchBooks;
</script>
</head>
<body>
<h1>电子书列表</h1>
<ul id="book-list"></ul>
</body>
</html>
8. 配置文件
在 application.properties
文件中,配置 H2 数据库。
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
结尾
以上就是使用 Spring Boot 实现电子书 CRUD 功能的完整示例。通过这个应用,我们可以方便地对电子书进行增、删、改、查操作,并在前端展示出电子书的列表。可以通过增强前端展示来进一步提升用户体验,例如添加样式、搜索功能等。