目录
最终效果图
前言:springboot是什么
一、实现类和接口类
在Book中设置图书的属性
BookRepository接口
BookServiceImpl实现类
BookService接口
BookController业务层
二、html搭建
连接MySQL
index.html 搭建基本框架
add_book.html搭建新增图书界面,通过添加的超链接进入界面
updata_book.html搭建更新图书界面,通过添加的超链接进入界面
query_book.html中设置了超链接跳转到查询图书的界面中
Spring Boot简化了开发人员对Spring框架的应用程序的搭建和配置过程,提供了一套简单易用的开发工具和规范,使开发人员能够更专注于业务逻辑的开发,而无需过多关注繁琐的配置和细节。
package com.lzzy.project.model;
import jakarta.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private String name;
@Column(name = "writer")
private String writer;
@Column(name = "state")
private String state;
@Column(name = "price")
private int price;
}
JpaRepository是Spring Data JPA框架提供的一个接口,它提供了许多用于操作数据库的方法,例如保存数据、查询数据、删除数据等。通过继承JpaRepository接口,BookRepository就可以使用这些方法来对Book实体对象进行持久化操作。
并且设置了模糊查询。
package com.lzzy.project.repository;
import com.lzzy.project.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookRepository extends JpaRepository {
@Query("SELECT b FROM Book b WHERE b.name LIKE %:keyword%")
List findByNameContaining(@Param("keyword") String keyword);
}
在BookServiceImpl中通过这些方法的实现,BookServiceImpl类成为了一个BookService接口的实现类,可以提供对书籍的保存、查询和删除等服务操作。
package com.lzzy.project.service;
import com.lzzy.project.model.Book;
import com.lzzy.project.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Override
public void saveBook(Book book) {this.bookRepository.save(book);}
@Override
public List getAllBook() {return bookRepository.findAll();}
@Override
public void deleteBookById(long id) {this.bookRepository.deleteById(id);}
//获取指定图书的id
@Override
public Book getBookById(long id){
//调用数据访问层查找指定ID的图书,返回Optional对象
Optional< Book > optional = bookRepository.findById(id);
Book book = null;
//如果存在指定id的图书
if (optional.isPresent()) {
//从Optional对象中获取图书对象
book = optional.get();
} else {
//否则抛出运行时异常
throw new RuntimeException(" :: " + id);
}
return book;
}
@Override
public Page findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
//设置排序参数,升序ASC/降序DESC?
Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
? Sort.by(sortField).ascending()
: Sort.by(sortField).descending();
//根据页号/每页记录数/排序依据返回某指定页面数据。
Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
return this.bookRepository.findAll(pageable);
}
@Override
public List QueryBook(String bookName) {
//将查询结果返回
return bookRepository.findByNameContaining(bookName);
}
}
在BookService中通过定义这些方法,BookService接口提供了一系列操作图书的服务接口,具体的实现类可以根据需要来实现这些方法来提供对图书的具体操作功能。
package com.lzzy.project.service;
import com.lzzy.project.model.Book;
import org.springframework.data.domain.Page;
import java.util.List;
public interface BookService {
//获取所有的图书
List getAllBook();
//新增/更新一本图书
void saveBook(Book book);
//删除指定id的图书
void deleteBookById(long id);
//获取指定图书的id
Book getBookById(long id);
//分页 + 排序
Page findPaginated(int pageNo, int pageSize, String sortField, String sortDirection);
// 按名称查询
List QueryBook(String bookName);
}
在BookController中,使用@Autowired注解将BookService注入到该类的booksService属性中。通过依赖注入,BookController可以使用BookService中定义的方法来处理业务逻辑。
@Autowired注解告诉Spring框架将BookService的实例自动注入到booksService属性中,这样在BookController中就可以直接使用booksService来调用BookService中定义的方法了。
这样,BookController就可以与视图层(如前端页面)进行交互
package com.lzzy.project.controller;
import com.lzzy.project.model.Book;
import com.lzzy.project.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
public class BookController {
@Autowired
private BookService booksService;
// @GetMapping("/")
// public String viewHomePage(Model model) {
// model.addAttribute("listBook", booksService.getAllBook());
// return "index";
// }
@GetMapping("/")
public String viewHomePage(Model model) {
return findPaginated(1, "id", "asc", model);
}
//新增图书
@GetMapping("/showNewBookForm")
public String showNewBookForm(Model model) {
Book book = new Book();
model.addAttribute("book", book);
return "add_book";
}
//保存图书
@PostMapping("/saveBook")
public String saveBook(@ModelAttribute("book") Book book) {
booksService.saveBook(book);
return "redirect:/";
}
//更新图书
@GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {
Book book = booksService.getBookById(id);
model.addAttribute("book", book);
return "update_book";
}
//删除图书
@GetMapping("/deleteBook/{id}")
public String deleteEmployee(@PathVariable(value = "id") long id) {
this.booksService.deleteBookById(id);
return "redirect:/";
}
//获取分页数据
@GetMapping("/page/{pageNo}")
public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
@RequestParam("sortField") String sortField,
@RequestParam("sortDir") String sortDir,
Model model) {
int pageSize = 5;
Page page = booksService.findPaginated(pageNo, pageSize, sortField, sortDir);
List listBook = page.getContent();
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", page.getTotalPages());
model.addAttribute("totalItems", page.getTotalElements());
model.addAttribute("sortField", sortField);
model.addAttribute("sortDir", sortDir);
model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
model.addAttribute("listBook", listBook);
return "index";
}
//按书名查询
@GetMapping("/query")
public String queryBookName(@RequestParam("bookName") String bookName, Model model){
List books = booksService.QueryBook(bookName);
model.addAttribute("books", books);
return "query_book";
}
}
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username= root
spring.datasource.password= 123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# for Spring Boot 2
# spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
# for Spring Boot 3
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
#?????hibernate-sql
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
图书管理系统
添加图书
更新图书
查询结果
运行后的效果就出来了