图书管理系统(springboot+mybatisplus)大致思路及遇到的问题总结

目录

一. 创建maven项目 数据库连接 导入依赖 编辑.yml

二. 创建实体类

1.Book类

2. Admin类

​编辑 3. User类

4. BorrowInfo类

​编辑 5. Result类(可随意增加方法)

 三. 创建mapper

1. BookMapper

2. AdminMapper

 3.UserMapper

4. BorrowMapper

四. 创建mapper.xml

1. AdminMapper.xml

2. UserMapper.xml

 五. 创建Service

1.BookService

2. AdminService

3. UserService

​编辑 4. BorrowService

六. 创建ServiceImpl

1. BookServiceImpl

2. AdminServiceImpl

​编辑 3. UserServiceImpl

4. BorrowServiceImpl

七. 创建controller

1. BookController

2. AdminController

3. UserController

4. BorrowController

八. 创建knife4j配置类

九. 问题总结

任务概述

项目功能展示

数据库设计 

接口设计

 

一. 创建maven项目 数据库连接 导入依赖 编辑.yml

二. 创建实体类

1.Book类

2. Admin类

 3. User类

4. BorrowInfo类

 5. Result类(可随意增加方法)

 

 三. 创建mapper

1. BookMapper

@Mapper
public interface BookMapper extends BaseMapper<Book> {

    @Update("UPDATE book SET quantity = quantity - 1 WHERE book_id = #{id}")
    void decreaseBookQuantity(@Param("id") int book_id);

    @Update("UPDATE book SET quantity = quantity + 1 WHERE book_id = #{id}")
    void increaseBookQuantity(@Param("id") int book_id);

    @Select("SELECT * FROM book")
    List<Book> getAllBook();

    @Insert("INSERT INTO book (title, author, isbn) VALUES (#{title}, #{author}, #{isbn})")
    void save(Book book);

    @Update("UPDATE book SET title = #{title}, author = #{author}, isbn = #{isbn} WHERE id = #{id}")
    void update(Book book);

    @Delete("DELETE FROM book WHERE book_id = #{bookId}")
    void delete(@Param("bookId") int book_id);

    @Select("SELECT * FROM book WHERE book_id = #{id}")
    Book getById(@Param("id") int book_id);

    @Select("SELECT * FROM borrow_info WHERE user_id = #{id}")
    String getBorrowInfoByUserId(@Param("id") int user_id);

    @Select("SELECT * FROM book")
    List<Book> getAllBooks();
}

2. AdminMapper

@Mapper
public interface AdminMapper extends BaseMapper<Admin> {


    @Select("SELECT * FROM book")
    List<Book> getAllBooks();

    @Select("SELECT * FROM book WHERE book_id = #{bookId}")
    List<Book> getBookById(@Param("bookId") int book_id);

    @Insert("INSERT INTO book (book_id, book_author, book_name, book_introduction, book_price, quantity) VALUES " +
            "(#{book.id}, #{book.author}, #{book.name}, #{book.introduction}, #{book.price}, #{book.remain})")
    int addBook(@Param("book")Book book);

    /*@Update("UPDATE book SET book_author = #{book.author}, book_name = #{book.name}, " +
            "book_introduction = #{book.introduction}, book_price = #{book.price}," +
            " quantity = #{book.remain} WHERE book_id = #{book.id}")*/
    int updateBook(@Param("book") Book book);

    @Delete("DELETE FROM book WHERE book_id = #{bookId}")
    int deleteBook(@Param("bookId") int book_id);

    @Select("SELECT * FROM user")
    List<User> getAllUsers();

    @Select("SELECT * FROM user WHERE user_id = #{userId}")
    List<User> getUserById(@Param("userId") int user_id);

    /*@Update("UPDATE user SET user_name = #{user.username}, user_pwd = #{user.password}, user_gender = #{user.gender}," +
            " name = #{user.name}, user_address = #{user.address}, user_phone = #{user.phone} WHERE user_id = #{user.id}")*/
    int updateUser(@Param("user") User user);

    @Select("SELECT * FROM borrow_info WHERE user_id = #{userId}")
    List<BorrowInfo> getBorrowedBooks(@Param("userId") int userId);

    @Select("SELECT * FROM borrow_info WHERE user_id = #{userId} AND return_date IS NULL and borrow_date IS NOT NULL")
    List<BorrowInfo> getUnreturnedBooks(@Param("userId") int user_id);

    @Update("UPDATE admin SET admin_pwd = #{newPassword} WHERE admin_name = #{adminname}")
    int updateAdminPassword(@Param("adminname") String admin_name, @Param("newPassword") String newPassword);

   /* @Update("UPDATE admin SET admin_name = #{admin.username}, admin_pwd = #{admin.password} WHERE admin_id = #{admin.id}")*/
    int updateAdmin(@Param("admin") Admin admin);
}

 3.UserMapper

@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {


    @Insert("insert into user(user_id, user_name, user_pwd, name, user_gender, user_address, user_phone) " +
            "values(#{user.id}, #{user.username}, #{user.password}, #{user.name}, #{user.gender}, #{user.address}, #{user.phone})")
    @Transactional
    void register(@Param("user")  User user);
    //insert into 表名(表中字段) values (类中字段)
    /*@Transactional注解表示这个方法需要在一个事务中执行,即在这个方法内部的数据库操作要么全部成功,要么全部失败。
    如果有异常发生,事务会回滚到之前的状态,保证数据的一致性。*/


    @Select("select * from user where user_id = #{id}")
    List<User> getUserById(@Param("id") int user_id);//select * 的 返回的是List类型 不是User类型


    /*@Update("update user set user_name = #{user.username}, user_pwd = #{user.password}, name = #{user.name}," +
            " user_gender = #{user.gender}, user_address = #{user.address}, user_phone = #{user.phone} where user_id = #{user.id}")*/
    void updateUserInfo(@Param("user") User user);


    @Select("select * from book where book_name like #{book_name}")
    List<Book> searchBookByName(String book_name);

    @Select("select * from borrow_info where user_id = #{userId}")
    List<BorrowInfo> getBorrowInfoByUserId(@Param("userId") int user_id);

    @Insert("insert into borrow_info(user_id, book_id, borrow_date) values(#{userId}, #{bookId}, #{borrowDate})")
    void borrowBook(@Param("userId") int  user_id, @Param("bookId") int book_id, @Param("borrowDate") Date borrow_date);

    @Update("update borrow_info set return_date = #{returnDate} where borrow_id = #{borrowId} and user_id = #{userId} and book_id = #{bookId}")
    void returnBook(@Param("borrowId") int borrow_id, @Param("userId") int  user_id, @Param("bookId") int book_id);

    @Update("update book set quantity = quantity - 1 where bookId = #{bookId}")
    void decreaseBookQuantity(@Param("bookId") int bookId);

    @Update("update book set quantity = quantity + 1 where bookId = #{bookId}")
    void increaseBookQuantity(@Param("bookId") int bookId);


    @Select("select * from admin where admin_name = #{uname} and admin_pwd = #{pwd}")
    List<Admin> loginAdmin(@Param("uname")String admin_name, @Param("pwd")String admin_pwd);

    @Select("select * from user where user_name = #{uname} and user_pwd = #{pwd}")
    List<User> loginUser(@Param("uname")String user_name, @Param("pwd")String user_pwd);
}

4. BorrowMapper

@Mapper
public interface BorrowMapper extends BaseMapper<BorrowInfo > {


    @Insert("INSERT INTO borrow_info (borrow_id, book_id, user_id, borrow_date) VALUES (#{borrowId}, #{bookId}, #{userId}, #{borrowDate})")
    void borrowBook(@Param("borrowId") int borrow_id, @Param("bookId") int book_id, @Param("userId") int user_id, @Param("borrowDate") Date borrow_date) ;

    @Insert("INSERT INTO borrow_info (borrow_id,book_id, user_id, return_date) VALUES (#{borrowId}, #{bookId}, #{userId}, #{returnDate})")
     void returnBook(@Param("borrowId") int borrow_id, @Param("bookId") int book_id, @Param("userId") int user_id, @Param("returnDate") Date return_date);

    @Select("select * from book where user_id = #{user_id}")
     String getBorrowInfoByUserId(@Param("user_id") int user_id);

    @Select("SELECT * FROM book WHERE book_id = #{bookId}")
    Book getBookInfoById(@Param("bookId") int book_id);
}

 

四. 创建mapper.xml

1. AdminMapper.xml

2. UserMapper.xml

 五. 创建Service

1.BookService

2. AdminService

3. UserService

 4. BorrowService

六. 创建ServiceImpl

1. BookServiceImpl

2. AdminServiceImpl

 

 3. UserServiceImpl

 

4. BorrowServiceImpl

七. 创建controller

1. BookController

@RestController
@RequestMapping(value = "/books")
@Api(tags = "图书管理")
public class BookController {

    @Autowired
    private IBookService bookService;

    @ApiOperation("新增图书")
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean flag = bookService.save(book);
        return new Result(flag, flag ? "添加成功" : "添加失败");
    }

    @ApiOperation("按序号删除图书")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = bookService.removeById(id);
        return new Result(flag, flag ? "删除成功" : "删除失败");
    }

    @ApiOperation("修改图书信息")
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.updateById(book);
        return new Result(flag, flag ? "修改成功" : "修改失败");
    }

    @ApiOperation("根据ID获取图书信息")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        if (book != null) {
            return new Result(true, book);
        } else {
            return new Result(false, "Book not found");
        }
    }

    @ApiOperation("分页获取全部图书信息")
    @GetMapping("/all")
    public ResponseEntity<Result> getAllBooks(@RequestParam int pageNum, @RequestParam int pageSize) {
        List<Book> books = bookService.getAllBooks(pageNum, pageSize);
        if (books != null && !books.isEmpty()) {
            return ResponseEntity.ok(new Result(true, "Success", books));
        } else {
            return ResponseEntity.ok(new Result(false, "No books found", (List) null));
        }
    }

    @ApiOperation("减少图书数量")
    @PostMapping("/decreaseBookQuantity")
    public Result decreaseBookQuantity(@RequestParam int bookId) {
        bookService.decreaseBookQuantity(bookId);
        return new Result(true, "Book quantity decreased");
    }

    @ApiOperation("增加图书数量")
    @PostMapping("/increaseBookQuantity")
    public Result increaseBookQuantity(@RequestParam int bookId) {
        bookService.increaseBookQuantity(bookId);
        return new Result(true, "Book quantity increased");
    }

 }

2. AdminController

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员功能")
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private IBookService bookService;


    @GetMapping("/books/all")
    @ApiOperation(value = "获取全部书籍")
    public ResponseEntity<Result> getAllBooks(@RequestParam int pageNum, @RequestParam int pageSize) {
        List<Book> books = bookService.getAllBooks(pageNum, pageSize);
        if (books != null && !books.isEmpty()) {
            return ResponseEntity.ok(new Result(true, "Success",  books));
        } else {
            return ResponseEntity.ok(new Result(false, "No books found", (List) null));
        }
    }

    @GetMapping("/books/{id}")
    @ApiOperation(value = "根据ID获取书籍")
    public Result getBookById(@PathVariable int id) {
        List<Book> book = adminService.getBookById(id);
        if (book != null) {
            return new Result(true, book);
        } else {
            return new Result(false, "Book not found");
        }
    }

    @PostMapping("/books/save")
    @ApiOperation(value = "添加书籍")
    public Result addBook(@RequestBody Book book) {
        try {
            adminService.saveBook(book);
            return new Result(true, "Book added successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to add book");
        }
    }

    @PostMapping("/books/update")
    @ApiOperation(value = "修改书籍信息")
    public Result updateBook(@RequestBody Book book) {
        try {
            adminService.updateBook(book);
            return new Result(true, "Book updated successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to update book");
        }
    }

    @DeleteMapping("/books/delete/{bookId}")
    @ApiOperation(value = "删除书籍")
    public Result deleteBook(@PathVariable int bookId) {
        try {
            adminService.deleteBook(bookId);
            return new Result(true, "Book deleted successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to delete book");
        }
    }

    @GetMapping("/user/{userId}")
    @ApiOperation(value = "根据ID获取用户")
    public Result getUserById(@PathVariable int userId) {
        List<User> user = adminService.getUserById(userId);
        if (user != null) {
            return new Result(true, user);
        } else {
            return new Result(false, "User not found");
        }
    }

    @GetMapping("/users")
    @ApiOperation(value = "获取所有用户")
    public Result getAllUsers() {
        List<User> users = adminService.getAllUsers();
        if (users != null) {
            return new Result(true, users);
        } else {
            return new Result(false, "Failed to get all users");
        }
    }

    @PostMapping("/user/update")
    @ApiOperation(value = "修改用户信息")
    public Result updateUser(@RequestBody User user) {
        try {
            adminService.updateUser(user);
            return new Result(true, "User updated successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to update user");
        }
    }

    @GetMapping("/user/{userId}/borrowed")
    @ApiOperation(value = "获取已借阅的书籍")
    public Result getBorrowedBooks(@PathVariable int userId) {
        List<BorrowInfo> borrowedBooks = adminService.getBorrowedBooks(userId);
        if (borrowedBooks != null) {
            return new Result(true, borrowedBooks);
        } else {
            return new Result(false, "Failed to get borrowed books");
        }
    }

    @GetMapping("/user/{userId}/unreturned")
    @ApiOperation(value = "获取用户未归还的书籍")
    public Result getUnreturnedBooks(@PathVariable int userId) {
        List<BorrowInfo> unreturnedBooks = adminService.getUnreturnedBooks(userId);
        if (unreturnedBooks != null) {
            return new Result(true, unreturnedBooks);
        } else {
            return new Result(false, "Failed to get unreturned books");
        }
    }

    @PostMapping("/admin/updatePassword")
    @ApiOperation(value = "修改管理员密码")
    public Result updateAdminPassword(@RequestParam String username, @RequestParam String newPassword) {
        try {
            adminService.updateAdminPassword(username, newPassword);
            return new Result(true, "Admin password updated successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to update admin password");
        }
    }

    @PostMapping("/admin/update")
    @ApiOperation(value = "修改管理员信息")
    public Result updateAdmin(@RequestBody Admin admin) {
        try {
            adminService.updateAdmin(admin);
            return new Result(true, "Admin updated successfully");
        } catch (Exception e) {
            return new Result(false, "Failed to update admin: " + e.getMessage());
        }
    }
}

3. UserController

@RestController
@RequestMapping("/user")
@Api(tags = "读者功能")
public class UserController {

    @Autowired
    private IUserService userService;

    Result result;

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestParam String username, @RequestParam String password) {
        List<Admin> admin = userService.loginAdmin(username, password);
        if (admin != null && !admin.isEmpty()) {
            return new Result(true, "Admin login successful", admin);
        } else {
            List<User> user = userService.loginUser(username, password);
            if (user != null && !user.isEmpty()) {
                return new Result(true, "User login successful", user);
            } else {
                return new Result(false, "Login failed");
            }
        }
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public Result registerUser(@RequestBody User user) {
        Result result = new Result();

        // 检查必填字段是否为空
        if (user.getId() == 0) {
            result.setSuccess(false);
            result.setMessage("Id不能为空");
            return result;
        }

        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("用户名不能为空");
            return result;
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("密码不能为空");
            return result;
        }
        if (user.getGender() == null || user.getGender().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("性别不能为空");
            return result;
        }
        if (user.getName() == null || user.getName().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("姓名不能为空");
            return result;
        }
        if (user.getAddress() == null || user.getAddress().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("地址不能为空");
            return result;
        }
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            result.setSuccess(false);
            result.setMessage("手机号不能为空");
            return result;
        }

        try {
            userService.register(user);
            result.setFlag(true);
            result.setMsg("注册成功");
        } catch (IllegalArgumentException e) {
            result.setFlag(false);
            result.setMsg(e.getMessage());
        }

        return result;
    }


    @GetMapping("/getUserById")
    @ApiOperation("根据ID查看用户信息")
    public Result getUserById(@RequestParam int id) {
        List<User> users = userService.getUserById(id);
        if (!users.isEmpty()) {
            return new Result(true, users);
        } else {
            return new Result(false, "User not found");
        }
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation("修改用户信息")
    public Result updateUserInfo(@RequestBody User user) {
        try {
            userService.updateUserInfo(user);
            return new Result(true, "User information updated");
        } catch (Exception e) {
            return new Result(false, "Update failed: " + e.getMessage());
        }
    }

    @GetMapping("/searchBookByName")
    @ApiOperation("根据书名搜索书籍")
    public Result searchBookByName(@RequestParam String name) {
        List<Book> books = userService.searchBookByName(name);

        // 过滤掉书籍列表中的null值
        List<Book> filteredBooks = new ArrayList<>();
        for (Book book : books) {
            if (book != null) {
                filteredBooks.add(book);
            }
        }

        return new Result(true, filteredBooks);
    }

    @GetMapping("/getBorrowInfo")
    @ApiOperation("根据用户ID获取用户借阅信息")
    public Result getBorrowInfoByUserId(@RequestParam int userId) {
        List<BorrowInfo> borrowInfoList = userService.getBorrowInfoByUserId(userId);
        return new Result(true, borrowInfoList);
    }

    @PostMapping("/returnBook")
    @ApiOperation("归还书籍")
    public Result returnBook(@RequestParam int borrow_id, @RequestParam int userId, @RequestParam int bookId) {
        try {
            userService.returnBook(borrow_id, userId, bookId);
            return new Result(true, "Book returned successfully");
        } catch (Exception e) {
            return new Result(false, "Return failed: " + e.getMessage());
        }
    }

    @PostMapping("/borrowBook")
    @ApiOperation("借阅书籍")
    public Result borrowBook(@RequestParam int borrowId, @RequestParam int userId, @RequestParam int bookId) {
        try {
            userService.borrowBook(borrowId, userId, bookId);
            return new Result(true, "Book borrowed successfully");
        } catch (Exception e) {
            return new Result(false, "Borrow failed: " + e.getMessage());
        }
    }
}

4. BorrowController

@RestController
@RequestMapping("/borrow")
@Api(tags = "借阅信息管理")
public class BorrowController {

    @Autowired
    private IBorrowService borrowService;

    @PostMapping("/borrowBook")
    @ApiOperation(value = "借阅书籍")
    public Result borrowBook(@RequestParam int borrowId, @RequestParam int bookId, @RequestParam int userId) {
        Book borrowedBook = borrowService.borrowBook(borrowId, bookId, userId); // 假设borrowService.borrowBook方法返回借阅的书籍信息
        if (borrowedBook != null) {
            return new Result(true, "Book borrowed successfully.", borrowedBook);
        } else {
            return new Result(false, "Failed to borrow book. Please check the input parameters.");
        }
    }

    @PostMapping("/returnBook")
    @ApiOperation(value = "归还书籍")
    public Result returnBook(@RequestParam int borrowId, @RequestParam int bookId, @RequestParam int userId) {
        borrowService.returnBook(borrowId, bookId, userId);
        return new Result(true, "Book returned successfully.");
    }

    @GetMapping("/getBorrowInfo")
    @ApiOperation(value = "根据用户id查找借阅信息")
    public Result getBorrowInfoByUserId(@RequestParam int userId) {
        String borrowInfoList = borrowService.getBorrowInfoByUserId(userId);
        return new Result(true, borrowInfoList);
    }
}

八. 创建knife4j配置类

九. 问题总结

1. springboot和knife4j的版本容易冲突 我选择的分别是2.6版本和3.0.3版本

2. 若用了Knife4j 必须把controller包加在配置里 并且实体类也需要加上注解

3.mybatisplus提供的接口可以直接继承 更方便

4. 修改信息操作更推荐用.xml来做  因为有可能修改的只是部分信息 

5.短sql注解开发更方便  动态sql开发更灵活

6. 短sql  如果传入的参数是一个类  那在sql中需要用类.变量名 否则找不到数据

7.很多时候 如果运行失败报错为 “找不到什么什么”(很离谱的错误)  那大概率是你的pom.xml中的哪个依赖的版本修改了

8.Controller返回Service的方法  得到的对象先判断是不是为空  返回给result处理   

   Service接口写好方法名 不写方法体 

   ServiceImpl写返回mapper.方法 

   Mapper写sql语句

  • 10
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值