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

MyBatis版图书管理系统

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

项目结构如下:

在这里插入图片描述
要导入的包:
在这里插入图片描述

Bean

Book.java

package bean;public class Book {private int bookId;//图书id private String bookName;//图书名称private double bookPrice;//图书价格private String bookAuthor;//图书作者private int num;//图书数量public int getBookId() {return bookId;}public void setBookId(int bookId) {this.bookId = bookId;}public String getBookName() {return bookName;}public void setBookName(String bookName) {this.bookName = bookName;}public double getBookPrice() {return bookPrice;}public void setBookPrice(double bookPrice) {this.bookPrice = bookPrice;}public String getBookAuthor() {return bookAuthor;}public void setBookAuthor(String bookAuthor) {this.bookAuthor = bookAuthor;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public Book(int bookId, String bookName, double bookPrice, String bookAuthor, int num) {super();this.bookId = bookId;this.bookName = bookName;this.bookPrice = bookPrice;this.bookAuthor = bookAuthor;this.num = num;}public Book() {super();}public Book(String bookName, double bookPrice, String bookAuthor, int num) {super();this.bookName = bookName;this.bookPrice = bookPrice;this.bookAuthor = bookAuthor;this.num = num;}@Overridepublic String toString() {return "Book [bookId=" + bookId + ", bookName=" + bookName + ", bookPrice=" + bookPrice + ", bookAuthor="+ bookAuthor + ", num=" + num + "]";}
}

BorrowBook.java

package bean;import java.util.Date;public class BorrowBook {private int boid;// 借阅序号private int bookId;// 图书idprivate int cardId;// 卡号private Date borrowTime;// 借出时间private Date givebackTime;// 归还时间private int bolsTrue;// 0表示借出 1表示归还private Book book;// 根据图书id去拿到book对象public int getBoid() {return boid;}public void setBoid(int boid) {this.boid = boid;}public int getBookId() {return bookId;}public void setBookId(int bookId) {this.bookId = bookId;}public int getCardId() {return cardId;}public void setCardId(int cardId) {this.cardId = cardId;}public Date getBorrowTime() {return borrowTime;}public void setBorrowTime(Date borrowTime) {this.borrowTime = borrowTime;}public Date getGivebackTime() {return givebackTime;}public void setGivebackTime(Date givebackTime) {this.givebackTime = givebackTime;}public int getBolsTrue() {return bolsTrue;}public void setBolsTrue(int bolsTrue) {this.bolsTrue = bolsTrue;}public Book getBook() {return book;}public void setBook(Book book) {this.book = book;}public BorrowBook(int boid, int bookId, int cardId, Date borrowTime, Date givebackTime, int bolsTrue, Book book) {super();this.boid = boid;this.bookId = bookId;this.cardId = cardId;this.borrowTime = borrowTime;this.givebackTime = givebackTime;this.bolsTrue = bolsTrue;this.book = book;}public BorrowBook() {super();}@Overridepublic String toString() {return "BorrowBook [boid=" + boid + ", bookId=" + bookId + ", cardId=" + cardId + ", borrowTime=" + borrowTime+ ", givebackTime=" + givebackTime + ", bolsTrue=" + bolsTrue + ", book=" + book + "]";}}

Card.java

package bean;public class Card {private int cardId;//卡号private String cardName;//用户名private double cardMoney;//余额public int getCardId() {return cardId;}public void setCardId(int cardId) {this.cardId = cardId;}public String getCardName() {return cardName;}public void setCardName(String cardName) {this.cardName = cardName;}public double getCardMoney() {return cardMoney;}public void setCardMoney(double cardMoney) {this.cardMoney = cardMoney;}public Card(int cardId, String cardName, double cardMoney) {super();this.cardId = cardId;this.cardName = cardName;this.cardMoney = cardMoney;}public Card() {super();}@Overridepublic String toString() {return "Card [cardId=" + cardId + ", cardName=" + cardName + ", cardMoney=" + cardMoney + "]";}
}

Dao层

BookMapper.java

package dao;import java.util.List;import bean.Book;public interface BookMapper {// 添加图书public int insertBook(Book book);// 修改图书的库存public int updateBookNum(Book book);// 图书的查询// 0.根据图书id查询Bookpublic Book selectByBookId(int bookId);// 1.按照书名模糊查询public List<Book> selectByBookNameLike(String name);// 2.按照作者模糊查询public List<Book> selectByAuthorNameLike(String author);// 3.查询哪些书被全部借走了,书的数量为0public List<Book> selectBookNumZero(int num);// 查询所有图书,动态sql,选择图书public List<Book> selectAll(Book book);// 借书public int borrowBook(int bookId);// 还书public int returnBook(int bookId);
}

BorrowBookMapper .java

package dao;import java.util.List;
import java.util.Map;import bean.Book;
import bean.BorrowBook;public interface BorrowBookMapper {// 创建一条新的借书记录public int addBorrow(BorrowBook borrowBook);// 根据用户id查询所有借书记录,包括已归还和未归还的public List<BorrowBook> selectAll(int cardId);// 根据用户id查询所有未归还的记录public List<BorrowBook> selectByNotReturn(int cardId, int bolsTrue);// 更新借书记录public int updateBook(BorrowBook borrowBook);// 根据id查询borrowbook对象public BorrowBook selectByBoid(int boid);// 列出最受欢迎的前10本书List<Book> selectBookTop(int num);// 列出阅读书籍最多的前3名用户List<Map<String, Object>> selectCardTop(int num);
}

CardMapper .java

package dao;import java.util.List;import bean.Card;public interface CardMapper {// 增加: 添加卡public int insertCard(Card card);// 改:提供充值功能public int updateCard(Card card);// 查:根据卡号或者用户名查询用户卡信息public Card selectByCardIdOrCardName(Card card);// 查询所有用户,动态sql查询,借书功能的选择用户public List<Card> selectAll(Card card);
}

BookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 指向接口的类路径 -->
<mapper namespace="dao.BookMapper"><!-- 添加图书 --><insert id="insertBook" parameterType="book">insert intobook(book_name,book_price,book_author,book_num) values(#{bookName},#{bookPrice},#{bookAuthor},#{num})</insert><!-- 修改图书的库存 --><update id="updateBookNum" parameterType="book">update book<set><if test="num>=0">book_num=#{num}</if></set>where book_id=#{bookId}</update><resultMap id="bookmap" type="book"><id property="bookId" column="book_id" /><result property="bookName" column="book_name" /><result property="bookPrice" column="book_price" /><result property="bookAuthor" column="book_author" /><result property="num" column="book_num" /></resultMap><!-- 图书的查询 --><!-- 0.根据图书id查询Book --><select id="selectByBookId" parameterType="int"resultMap="bookmap">select * from book where book_id=#{v}</select><!-- 1.按照书名模糊查询 --><select id="selectByBookNameLike" parameterType="string"resultMap="bookmap"><bind name="v" value="'%'+_parameter+'%'" />select * from book where book_name like #{v}</select><!-- 2.按照作者模糊查询 --><select id="selectByAuthorNameLike" parameterType="string"resultMap="bookmap"><bind name="v" value="'%'+_parameter+'%'" />select * from book where book_author like #{v}</select><!-- 3.查询哪些书被全部借走了,书的数量为0 --><select id="selectBookNumZero" parameterType="book" resultMap="bookmap">select * from bookwhere book_num=#{num}</select><!-- 查询所有图书,动态sql,选择图书 --><select id="selectAll" parameterType="book"resultMap="bookmap">select * from book<where><if test="bookId!=0">and book_id=#{bookId}</if><if test="bookName!=null">and book_name=#{bookName}</if><if test="bookPrice!=0">and book_price=#{bookPrice}</if><if test="bookAuthor!=null">and book_author=#{bookAuthor}</if><if test="num!=0">and book_num=#{num}</if></where></select><!-- 借书 --><update id="borrowBook" parameterType="int">update book setbook_num=book_num-1 where book_id=#{v}</update><!-- 还书 --><update id="returnBook" parameterType="int">update book setbook_num=book_num+1 where book_id=#{v}</update>
</mapper>

BorrowBookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.BorrowBookMapper"><resultMap id="borrowbookmap" type="borrowbook"><result property="boid" column="boid" /><result property="bookId" column="book_id" /><result property="cardId" column="card_id" /><result property="borrowTime" column="borrowTime" /><result property="givebackTime" column="givebackTime" /><result property="bolsTrue" column="bolsTrue" /><!-- 一对一映射到 Book 对象 --><association property="book" javaType="book"><id property="bookId" column="book_id" /><result property="bookName" column="book_name" /><result property="bookPrice" column="book_price" /><result property="bookAuthor" column="book_author" /><result property="num" column="book_num" /></association></resultMap><!-- 创建一条新的借书记录 --><insert id="addBorrow" parameterType="borrowbook">INSERT INTO borrowbook(book_id, card_id, borrowtime, givebacktime, bolstrue)VALUES(#{bookId}, #{cardId}, #{borrowTime}, #{givebackTime}, #{bolsTrue})</insert><!-- 根据用户id查询所有借书记录 --><select id="selectAll" parameterType="int"resultMap="borrowbookmap">SELECT *FROM borrowbook left join book onbook.book_id=borrowbook.book_idWHERE card_id = #{v}</select><!-- 根据用户id查询所有未归还的记录 --><select id="selectByNotReturn" resultMap="borrowbookmap">SELECT*FROM borrowbookleft join book on book.book_id=borrowbook.book_idWHERE card_id =#{param1} and bolsTrue=#{param2}</select><!-- 根据id查询borrowbook对象 --><select id="selectByBoid" parameterType="int"resultMap="borrowbookmap">select * from borrowbook left join book onbook.book_id=borrowbook.book_idwhere boid=#{v}</select><!-- 更新借书记录 --><update id="updateBook" parameterType="borrowbook">update borrowbook<set><if test="bookId!=0">book_id=#{bookId},</if><if test="cardId!=0">card_id=#{cardId},</if><if test="borrowTime!=null">borrowTime=#{borrowTime},</if><if test="givebackTime!=null">givebackTime=#{givebackTime},</if><if test="bolsTrue!=0">bolsTrue=#{bolsTrue},</if></set>where boid=#{boid}</update><resultMap type="book" id="bookmap"><id property="bookId" column="book_id" /><result property="bookName" column="book_name" /><result property="bookPrice" column="book_price" /><result property="bookAuthor" column="book_author" /><result property="num" column="book_num" /></resultMap><!-- 列出最受欢迎的前?本书 --><select id="selectBookTop" parameterType="int" resultMap="bookmap">SELECTb.book_id,          <!-- 书籍的唯一标识 -->b.book_name,        <!-- 书籍的名称 -->b.book_author,      <!-- 书籍的作者 -->b.book_price,       <!-- 书籍的价格 -->COUNT(bb.book_id) AS borrow_count  <!-- 计算每本书的借阅次数 borrow_count -->FROM borrowbook bbJOIN book b ON bb.book_id = b.book_idGROUP BY b.book_idORDER BY borrow_count DESC  <!-- 按借阅次数降序排列,即借阅次数最多的书籍排在前面 -->LIMIT #{v}  <!-- 限制返回的记录数为前?本书籍 --></select><!-- 列出阅读书籍最多的前?名用户 --><select id="selectCardTop" parameterType="int" resultType="map"><!-- 选择卡号和借阅次数: -->SELECT bb.card_id,COUNT(bb.card_id) AS borrow_countFROM borrowbook bb<!-- 按照 card_id 对结果进行分组,以便统计每个用户的借阅次数 -->GROUP BY bb.card_id<!-- 将结果按照借阅次数(borrow_count)降序排列,将借阅次数最多的用户排在前面 -->ORDER BY borrow_count DESCLIMIT #{v}</select></mapper>

CardMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 指向接口的类路径 -->
<mapper namespace="dao.CardMapper"><!-- 增加: 添加卡 --><insert id="insertCard" parameterType="card">insert intocard(card_name,card_money) values(#{cardName},#{cardMoney})</insert><!--:提供充值功能 --><update id="updateCard" parameterType="card">update card<set><if test="cardName!=null">card_name=#{cardName},</if><if test="cardMoney!=null">card_money=#{cardMoney},</if></set>where card_id=#{cardId}</update><!--:根据卡号或者用户名查询用户卡信息 --><resultMap id="CardResultMap" type="card"><result property="cardId" column="card_id" /><result property="cardName" column="card_name" /><result property="cardMoney" column="card_money" /></resultMap><select id="selectByCardIdOrCardName" resultMap="CardResultMap">select * from card<where><if test="cardId!=0">and card_id=#{cardId}</if><if test="cardName!=null">and card_name=#{cardName}</if></where></select><!-- 查询所有用户,动态sql查询 --><select id="selectAll" parameterType="card"resultMap="CardResultMap">select * from card<where><if test="cardId!=0">and card_id=#{cardId}</if><if test="cardName!=null">and card_name=#{cardName}</if><if test="cardMoney">and card_money=#{cardMoney}</if></where></select>
</mapper>

Service层:

BookService.java

package service;import java.util.List;import bean.Book;public interface BookService {// 添加图书public boolean insertBook();// 修改图书的库存public boolean updateBookNum();// 图书的查询//0.根据图书id查询Bookpublic Book selectByBookId(int bookId);// 1.按照书名模糊查询public List<Book> selectByBookNameLike();// 2.按照作者模糊查询public List<Book> selectByAuthorNameLike();// 3.查询哪些书被全部借走了,书的数量为0public List<Book> selectBookNumZero(int num);// 查询所有图书,动态sql,选择图书public List<Book> selectAll(Book book);// 借书public boolean borrowBook(int bookId);// 还书public boolean returnBook(int bookId);
}

BorrowBookService.java

package service;import bean.BorrowBook;public interface BorrowBookService {// 创建一条新的借书记录public void addBorrow();// 查询所有借阅记录(包括未归还和归还的)public void selectAll();// 还书public void returnBorrow();// 列出最受欢迎的图书top10public void selectBookTop10();// 列出阅读书籍最多的用户top3public void selectCardTop3();
}

CardService.java

package service;import java.util.List;import bean.Card;public interface CardService {// 增加: 添加卡public boolean insertCard();// 改:提供充值功能public boolean updateCard();// 查:根据卡号或者用户名查询用户卡信息public Card selectByCardId();public Card selectByCardName();// 查询所有用户,动态sql查询public List<Card> selectAll(Card card);
}

Service.Impl接口实现类

BookServiceImpl.java

package service.impl;import java.util.List;
import java.util.Scanner;import org.apache.ibatis.session.SqlSession;import bean.Book;
import dao.BookMapper;
import service.BookService;
import utlis.SqlSessionUtils;public class BookServiceImpl implements BookService {// 获取Scannerstatic Scanner sc = new Scanner(System.in);@Overridepublic boolean insertBook() {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);System.out.println("请输入图书名称:");String bookName = sc.next();System.out.println("请输入图书价格:");double bookPrice = sc.nextDouble();System.out.println("请输入图书作者:");String bookAuthor = sc.next();System.out.println("请输入图书数量:");int num = sc.nextInt();Book book = new Book(bookName, bookPrice, bookAuthor, num);int count = bookMapper.insertBook(book);if (count > 0) {sqlSession.commit();System.out.println("新增图书成功");} else {sqlSession.rollback();System.out.println("新增图书失败");}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;}@Overridepublic boolean updateBookNum() {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);System.out.println("请输入你要修改的图书库存的id:");int bookId = sc.nextInt();// 查询原来的book信息Book book = selectByBookId(bookId);System.out.println("原数量" + book.getNum() + "请输入修改后的图书库存数量:");int num = sc.nextInt();if (num < 0) {System.out.println("你输入的数量小于0,修改失败!");return false;}book.setNum(num);int count = bookMapper.updateBookNum(book);if (count > 0) {sqlSession.commit();System.out.println("修改成功");} else {System.out.println("修改失败");sqlSession.rollback();}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;}@Overridepublic List<Book> selectByBookNameLike() {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);System.out.println("请输入书名:");String bookName = sc.next();List<Book> list = bookMapper.selectByBookNameLike(bookName);SqlSessionUtils.closeSqlSession(sqlSession);for (Book book : list) {System.out.println(book);}return list;}@Overridepublic List<Book> selectByAuthorNameLike() {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);System.out.println("请输入作者名:");String bookAuthor = sc.next();List<Book> list = bookMapper.selectByAuthorNameLike(bookAuthor);SqlSessionUtils.closeSqlSession(sqlSession);for (Book book : list) {System.out.println(book);}return list;}@Overridepublic List<Book> selectBookNumZero(int num) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);List<Book> list = bookMapper.selectBookNumZero(num);SqlSessionUtils.closeSqlSession(sqlSession);for (Book book : list) {System.out.println(book);}return list;}@Overridepublic List<Book> selectAll(Book book) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);List<Book> list = bookMapper.selectAll(book);SqlSessionUtils.closeSqlSession(sqlSession);for (Book books : list) {System.out.println(books);}return list;}@Overridepublic boolean borrowBook(int bookId) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);int count = bookMapper.borrowBook(bookId);if (count > 0) {sqlSession.commit();} else {sqlSession.rollback();}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;}@Overridepublic boolean returnBook(int bookId) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);int count = bookMapper.returnBook(bookId);if (count > 0) {sqlSession.commit();} else {sqlSession.rollback();}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;}@Overridepublic Book selectByBookId(int bookId) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);Book book = bookMapper.selectByBookId(bookId);return book;}}

BorrowBookServiceImpl

package service.impl;import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;import org.apache.ibatis.session.SqlSession;import bean.Book;
import bean.BorrowBook;
import bean.Card;
import dao.BookMapper;
import dao.BorrowBookMapper;
import dao.CardMapper;
import service.BookService;
import service.BorrowBookService;
import service.CardService;
import utlis.SqlSessionUtils;public class BorrowBookServiceImpl implements BorrowBookService {BookService bookService = new BookServiceImpl();CardService cardService = new CardServiceImpl();Scanner sc = new Scanner(System.in);// 用户查找public void selectUser() {System.out.println("请选择查找用户方式:");System.out.println("1.列出所有用户");System.out.println("2.条件查询");int cardchoice = sc.nextInt();Card querycard = new Card();if (cardchoice == 1) {// 展示所有用户cardService.selectAll(querycard); // 这里传入null表示查询所有用户} else if (cardchoice == 2) {// 条件查询System.out.println("请选择查询条件:");System.out.println("1. 按用户ID查询");System.out.println("2. 按用户名查询");int searchChoice = sc.nextInt();if (searchChoice == 1) {System.out.println("请输入用户ID:");int cardId = sc.nextInt();querycard.setCardId(cardId);} else if (searchChoice == 2) {System.out.println("请输入用户名:");String username = sc.next();querycard.setCardName(username); // 假设Card类有setCardName方法}// 调用服务层方法查询cardService.selectAll(querycard);}}// 图书查找public void selectBook() {// 图书查找System.out.println("请选择查找图书方式:");System.out.println("1.列出所有图书");System.out.println("2.条件查询");int bookchoice = sc.nextInt();Book querybook = new Book();if (bookchoice == 1) {// 展示所有用户bookService.selectAll(querybook); // 这里传入null表示查询所有图书} else if (bookchoice == 2) {// 条件查询System.out.println("请选择查询条件:");System.out.println("1. 按图书id查询");System.out.println("2. 按书名查询");System.out.println("3. 按图书价格查询");System.out.println("4. 按图书作者查询");int searchChoice = sc.nextInt();if (searchChoice == 1) {System.out.println("请输入图书ID:");int bookId = sc.nextInt();querybook.setBookId(bookId);} else if (searchChoice == 2) {System.out.println("请输入书名:");String bookName = sc.next();querybook.setBookName(bookName);} else if (searchChoice == 3) {System.out.println("请输入图书价格:");double bookPrice = sc.nextDouble();querybook.setBookPrice(bookPrice);} else if (searchChoice == 4) {System.out.println("请输入图书作者:");String bookAuthor = sc.next();querybook.setBookAuthor(bookAuthor);}// 调用服务层方法查询bookService.selectAll(querybook);}}// 借书@Overridepublic void addBorrow() {
//		selectUser();// 1.查找借书的人是谁// 根据用户id查询card对象Card card = cardService.selectByCardId();//		selectBook();// 2.根据图书id查询book对象System.out.println("请输入要借的书籍的id");int bookId = sc.nextInt();Book book = bookService.selectByBookId(bookId);System.out.println(book);// 2.1判断图书的数量是否为0,为0无法借阅if (book.getNum() == 0) {System.out.println("这本书被借光了,试试借阅其他书籍吧~");return;}// 3.判断,所借书的价格是否小于或等于书卡的余额,是借出,否提示用户余额不足if (book.getBookPrice() <= card.getCardMoney()) {SqlSession sqlSession = SqlSessionUtils.getSqlSession();// 3.1借书后,将book表的书的数量-1BookMapper bookmapper = sqlSession.getMapper(BookMapper.class);int totalNum = book.getNum() - 1;book.setNum(totalNum);int bookcount = bookmapper.updateBookNum(book);if (bookcount > 0) {sqlSession.commit();} else {sqlSession.rollback();}// 3.2在borrowbook表中新增一条记录BorrowBookMapper borrowBookMapper = sqlSession.getMapper(BorrowBookMapper.class);BorrowBook borrowBook = new BorrowBook();borrowBook.setBookId(book.getBookId());borrowBook.setCardId(card.getCardId());borrowBook.setBorrowTime(new Date());borrowBook.setGivebackTime(null);borrowBook.setBoid(0);int borrowCount = borrowBookMapper.addBorrow(borrowBook);if (borrowCount > 0) {sqlSession.commit();} else {sqlSession.rollback();}} else {System.out.println("借书失败,余额不足~");return;}}// 还书@Overridepublic void returnBorrow() {// 1.列出用户的借书记录。System.out.println("请输入你的借书卡id:");int cardId = sc.nextInt();SqlSession sqlSession = SqlSessionUtils.getSqlSession();BorrowBookMapper borrowBookMapper = sqlSession.getMapper(BorrowBookMapper.class);List<BorrowBook> list = borrowBookMapper.selectByNotReturn(cardId, 0);if (list.size() == 0) {System.out.println("没有找到该用户!");return;}for (BorrowBook borrowBook : list) {System.out.println(borrowBook);}// 2.用户选择要还的借书记录。System.out.println("请选择你要还的书的记录id");int boid = sc.nextInt();BorrowBook borrowBook = borrowBookMapper.selectByBoid(boid);if (borrowBook.getBolsTrue() == 1) {System.out.println("你的书已经被还了,谢谢哈~");return;}// 3.根据图书id更新end时间borrowBook.setGivebackTime(new Date());// 4.计算借书时间和还书时间的差值,进行计费,1分钟1块钱,扣除书卡中的余额// 获取时间戳Date borrowTime = borrowBook.getBorrowTime();Date givebackTime = borrowBook.getGivebackTime();// 计算时间差long timeDiffInMillis = givebackTime.getTime() - borrowTime.getTime();// 转换为分钟long Minutes = TimeUnit.MILLISECONDS.toMinutes(timeDiffInMillis);// 计算价格,1分钟一块钱double feeMin = 1.0;double totalCost = Minutes * feeMin;System.out.println("借书时间:" + borrowTime);System.out.println("还书时间:" + borrowTime);System.out.println("借书时长:" + Minutes);System.out.println("应付费用:" + totalCost + "元");// 5.去查询用户的钱是多少CardMapper cardmapper = sqlSession.getMapper(CardMapper.class);Card card = new Card();card.setCardId(cardId);Card cardMoney = cardmapper.selectByCardIdOrCardName(card);System.out.println("卡号为" + cardId + "的余额为" + cardMoney.getCardMoney());// 5.1如果cardMoney大于应付费用,就可以进行还书,,钱扣除,更改还书状态,书的数量+1if (cardMoney.getCardMoney() > totalCost) {double Moneyresult = cardMoney.getCardMoney() - totalCost;// 重新赋值cardMoney.setCardMoney(Moneyresult);// 5.1.1更新card表余额int cardM = cardmapper.updateCard(cardMoney);if (cardM > 0) {sqlSession.commit();System.out.println("余额更新成功");} else {sqlSession.rollback();System.out.println("余额更新失败");}// 5.1.2更新图书的数量BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);// 查询书Book book = bookMapper.selectByBookId(borrowBook.getBookId());System.out.println(book);// 给书的数量+1int totalbook = book.getNum() + 1;book.setNum(totalbook);int bookM = bookMapper.updateBookNum(book);if (bookM > 0) {sqlSession.commit();System.out.println("书籍数量更新成功");} else {sqlSession.rollback();System.out.println("书籍数量更新失败");}// 5.1.3更新borrowbook表的借阅状态和还书时间borrowBook.setBolsTrue(1);int borrowM = borrowBookMapper.updateBook(borrowBook);if (borrowM > 0) {sqlSession.commit();System.out.println("状态和归还时间更新成功");} else {sqlSession.rollback();System.out.println("状态和归还时间更新失败");}} else {// 5.2如果cardMoney小于应付费用,则提示充值,还书失败System.out.println("余额不足,还书失败");// 6.1查询book表中书的价格BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);Book book = bookMapper.selectByBookId(borrowBook.getBookId());if (book == null) {System.out.println("图书信息不存在!");return;}double bookPrice = book.getBookPrice();System.out.println("图书价格为:" + bookPrice + "元");// 6.2更新card表中的余额// 6.2 更新卡余额System.out.println("你确定要买断这本书吗?y/n");String buyResponse = sc.next();if (buyResponse.equalsIgnoreCase("y")) {if (cardMoney.getCardMoney() >= bookPrice) {// 从卡余额中扣除图书价格double newBalance = cardMoney.getCardMoney() - bookPrice;cardMoney.setCardMoney(newBalance);// 更新 card 表中的余额int cardUpdate = cardmapper.updateCard(cardMoney);if (cardUpdate > 0) {sqlSession.commit();System.out.println("余额更新成功,图书已买断!");} else {sqlSession.rollback();System.out.println("余额更新失败");}// 更新 borrowBook 表中的还书状态borrowBook.setGivebackTime(new Date());borrowBook.setBolsTrue(2);//假设状态2为买断这本书的情况int borrowUpdate = borrowBookMapper.updateBook(borrowBook);if (borrowUpdate > 0) {sqlSession.commit();System.out.println("还书状态更新成功");} else {sqlSession.rollback();System.out.println("还书状态更新失败");}} else {System.out.println("余额不足,无法买断图书!");}} else {System.out.println("图书买断取消。");}}}@Overridepublic void selectAll() {System.out.println("请输入你的用户id");int cardId = sc.nextInt();SqlSession sqlSession = SqlSessionUtils.getSqlSession();BorrowBookMapper borrowBookMapper = sqlSession.getMapper(BorrowBookMapper.class);List<BorrowBook> list = borrowBookMapper.selectAll(cardId);for (BorrowBook borrowBook : list) {System.out.println(borrowBook);}SqlSessionUtils.closeSqlSession(sqlSession);}@Overridepublic void selectBookTop10() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();System.out.println("借阅最多的书TOP10");BorrowBookMapper borrowBookMapper = sqlSession.getMapper(BorrowBookMapper.class);List<Book> list = borrowBookMapper.selectBookTop(10);for (Book book : list) {System.out.println(book);}SqlSessionUtils.closeSqlSession(sqlSession);}@Overridepublic void selectCardTop3() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();BorrowBookMapper borrowBookMapper = sqlSession.getMapper(BorrowBookMapper.class);List<Map<String, Object>> list = borrowBookMapper.selectCardTop(3);System.out.println("读者借阅数量TOP3");for (Map<String, Object> map : list) {int cardId = (int) map.get("card_id");Long borrowCount = (Long) map.get("borrow_count");System.out.println("用户id" + cardId + ", 借书数量" + borrowCount);}SqlSessionUtils.closeSqlSession(sqlSession);}
}

CardServiceImpl.java

package service.impl;import java.util.List;
import java.util.Scanner;import org.apache.ibatis.session.SqlSession;import bean.Card;
import dao.CardMapper;
import service.CardService;
import utlis.SqlSessionUtils;public class CardServiceImpl implements CardService {Scanner sc = new Scanner(System.in);@Overridepublic boolean insertCard() {Card card = new Card();System.out.println("请输入用户名:");String cardName = sc.next();int cardMoney = 0;card.setCardName(cardName);card.setCardMoney(cardMoney);// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);int count = cardMapper.insertCard(card);if (count > 0) {sqlSession.commit();System.out.println("添加成功");} else {sqlSession.rollback();System.out.println("添加失败");}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;}@Overridepublic boolean updateCard() {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);Card querycard = new Card();System.out.println("请输入你要充值的id:");int cardId = sc.nextInt();if (cardId < 0) {System.out.println("你的输入有误~");return false;}querycard.setCardId(cardId);// 根据cardId去查询有没有这个用户Card card = cardMapper.selectByCardIdOrCardName(querycard);if (card != null) {System.out.println("余额" + card.getCardMoney() + "请输入你要充值的金额:");double cardMoney = sc.nextDouble();if (cardMoney < 0) {System.out.println("你要充值的金额不能小于0");return false;}// 原来卡的金额+要充值的金额double sum = cardMoney + card.getCardMoney();System.out.println(sum);card.setCardMoney(sum);int count = cardMapper.updateCard(card);if (count > 0) {sqlSession.commit();System.out.println("充值成功");} else {sqlSession.rollback();System.out.println("充值失败");}SqlSessionUtils.closeSqlSession(sqlSession);return count > 0;} else {System.out.println("没有这个用户~");return false;}}@Overridepublic Card selectByCardId() {Card card = new Card();System.out.println("请输入你的卡号id:");int cardId = sc.nextInt();card.setCardId(cardId);// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);Card result = cardMapper.selectByCardIdOrCardName(card);SqlSessionUtils.closeSqlSession(sqlSession);if (result != null) {System.out.println(result);} else {System.out.println("没有找到这个用户!");}return result;}@Overridepublic Card selectByCardName() {Card card = new Card();System.out.println("请输入你的用户名");String cardName = sc.next();card.setCardName(cardName);// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);Card result = cardMapper.selectByCardIdOrCardName(card);SqlSessionUtils.closeSqlSession(sqlSession);if (result != null) {System.out.println(result);} else {System.out.println("没有找到这个用户!");}return result;}@Overridepublic List<Card> selectAll(Card card) {// 获取sqlSessionSqlSession sqlSession = SqlSessionUtils.getSqlSession();CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);List<Card> list = cardMapper.selectAll(card);SqlSessionUtils.closeSqlSession(sqlSession);for (Card cards : list) {System.out.println(cards);}return list;}}

Utlis层:

SqlSessionUtils.java

package utlis;import java.io.IOException;
import java.io.InputStream;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtils {static SqlSessionFactory factory = null;static {try {// 1.读取配置文件InputStream is = Resources.getResourceAsStream("mybatis-config.xml");// 2.生产sqlSession的工厂factory = new SqlSessionFactoryBuilder().build(is);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static SqlSession getSqlSession() {// 3.返回sqlSession对象return factory.openSession();}public static void closeSqlSession(SqlSession sqlSession) {// 4.释放资源sqlSession.close();}
}

View层

Menu.java

package View;public class Menu {public void displayMainMenu() {System.out.println("===== 图书管理系统 =====");System.out.println("1. 图书管理");System.out.println("2. 借书卡管理");System.out.println("3. 借书");System.out.println("4. 还书");System.out.println("5. 统计数据");System.out.println("6. 退出");System.out.print("请选择操作:");}public void displayBookManagementMenu() {System.out.println("===== 图书管理 =====");System.out.println("0. 查询所有图书");System.out.println("1. 添加图书");System.out.println("2. 修改图书库存");System.out.println("3. 根据作者名查询图书");System.out.println("4. 根据书名查询图书");System.out.println("5. 查询被借空的图书");System.out.println("6. 返回主菜单");System.out.print("请选择操作:");}public void displayCardManagementMenu() {System.out.println("===== 借书卡管理 =====");System.out.println("1. 添加借书卡");System.out.println("2. 充值借书卡");System.out.println("3. 根据卡号查询借书卡");System.out.println("4. 根据用户名查询借书卡");System.out.println("5. 返回主菜单");System.out.print("请选择操作:");}public void displayBorrowMenu() {System.out.println("===== 借书 =====");System.out.println("1. 列出所有用户");System.out.println("2. 根据条件查询用户");System.out.println("3. 列出所有图书");System.out.println("4. 根据条件查询图书");System.out.println("5. 借阅图书");System.out.println("6. 返回主菜单");System.out.print("请选择操作:");}public void displayReturnMenu() {System.out.println("===== 还书 =====");System.out.println("1. 列出借阅记录");System.out.println("2. 归还图书");System.out.println("3. 返回主菜单");System.out.print("请选择操作:");}public void displayStatisticsMenu() {System.out.println("===== 统计数据 =====");System.out.println("1. 最受欢迎的图书Top10");System.out.println("2. 阅读书籍最多的用户Top3");System.out.println("3. 返回主菜单");System.out.print("请选择操作:");}
}

Input.java

package View;import java.util.Scanner;import bean.Book;
import service.BookService;
import service.BorrowBookService;
import service.CardService;
import service.impl.BookServiceImpl;
import service.impl.BorrowBookServiceImpl;
import service.impl.CardServiceImpl;public class Input {private Menu menu = new Menu();private Scanner sc = new Scanner(System.in);// 服务类private BookService bookService = new BookServiceImpl();private CardService cardService = new CardServiceImpl();private BorrowBookService borrowBookService = new BorrowBookServiceImpl();public void start() {boolean exit = false;while (!exit) {menu.displayMainMenu();int choice = sc.nextInt();switch (choice) {case 1:bookManagement();break;case 2:cardManagement();break;case 3:borrowBook();break;case 4:returnBook();break;case 5:viewStatistics();break;case 6:exit = true;System.out.println("退出系统");break;default:System.out.println("无效的选项,请重新选择。");}}}private void bookManagement() {boolean back = false;while (!back) {menu.displayBookManagementMenu();int choice = sc.nextInt();switch (choice) {case 0:// 查询所有图书Book book = new Book();bookService.selectAll(book);break;case 1:// 调用bookService添加图书bookService.insertBook();break;case 2:// 调用bookService修改库存bookService.updateBookNum();break;case 3:// 调用bookService按照作者模糊查询bookService.selectByAuthorNameLike();break;case 4:// 调用bookServicei.按图书名模糊查询bookService.selectByBookNameLike();break;case 5:// 调用bookService查询被借空的图书int num = 0;bookService.selectBookNumZero(num);break;case 6:back = true;break;default:System.out.println("无效的选项,请重新选择。");}}}private void cardManagement() {boolean back = false;while (!back) {menu.displayCardManagementMenu();int choice = sc.nextInt();switch (choice) {case 1:// 调用cardService添加借书卡cardService.insertCard();break;case 2:cardService.updateCard();// 调用cardService充值借书卡break;case 3:// 调用cardService查询借书卡信息cardService.selectByCardId();break;case 4:// 调用cardService查询借书卡信息cardService.selectByCardName();break;case 5:back = true;break;default:System.out.println("无效的选项,请重新选择。");}}}private void borrowBook() {borrowBookService.addBorrow();boolean back = true;}private void returnBook() {boolean back = false;while (!back) {menu.displayReturnMenu();int choice = sc.nextInt();switch (choice) {case 1:borrowBookService.selectAll();break;case 2:// 归还图书borrowBookService.returnBorrow();break;case 3:back = true;break;default:System.out.println("无效的选项,请重新选择。");}}}private void viewStatistics() {boolean back = false;while (!back) {menu.displayStatisticsMenu();int choice = sc.nextInt();switch (choice) {case 1:// 列出最受欢迎的图书Top10borrowBookService.selectBookTop10();break;case 2:// 列出阅读书籍最多的用户Top3borrowBookService.selectCardTop3();break;case 3:back = true;break;default:System.out.println("无效的选项,请重新选择。");}}}
}

Application.java

package View;public class Application {public static void main(String[] args) {// 实例化 input对象Input input = new Input();// 调用 start 方法,启动系统input.start();}
}

配置文件

在这里插入图片描述

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bookmybatis?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=12345678

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

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><properties resource="jdbc.properties"></properties><typeAliases><!-- 给单个类起别名 --><!-- <typeAlias alias="Student" type="bean.Student"/> --><!-- 批量别名定义,包扫描,别名为类名,扫描整个包下的类 --><package name="bean"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></dataSource></environment></environments><mappers><!-- 注册sqlmapper文件 --><!-- 1.同包 接口和sqlMapper2.同名 接口和sqlMapper3.sqlMapper的namespace指向接口的类路径--><!-- <mapper resource="mapper/StudentMapper.xml" /> --><!-- <mapper class="mapper.StudentMapper"/>--><package name="dao"/></mappers>
</configuration>

http://www.mrgr.cn/news/62289.html

相关文章:

  • 提示工程(Prompt Engineering)指南(进阶篇)
  • 【网络面试篇】TCP与UDP类
  • 安全见闻-web安全
  • 使用Docker Compose简化微服务部署
  • uniapp renderjs页面传值
  • Git 常用命令与开发流程总结
  • 【渗透测试】01-信息收集-名词概念
  • 算法复杂度分析:深入剖析最好、最坏、平均、均摊时间复杂度
  • Linux学习_11
  • 勒索软件通过易受攻击的 Cyber​​Panel 实例攻击网络托管服务器
  • Linux学习_8
  • Swarm-LIO: Decentralized Swarm LiDAR-inertial Odometry论文翻译
  • 【模型学习之路】手写+分析bert
  • mysql使用DELIMITER,创建触发器、存储过程、存储函数
  • Spring Cloud --- 引入Seata分布式事务
  • Linux网络命令:系统中用于显示和操作 ARP缓存表的命令arp详解
  • C语言——八股文(笔试面试题)
  • Redis 主从同步 问题
  • 使用Go构建以太坊
  • 机器学习与神经网络荣获2024年诺贝尔物理学奖:意义与未来展望
  • 设计模式-建造者模式(代码实现、源码级别应用、使用场景)
  • At dp综合
  • 算法训练(leetcode)二刷第十三天 | 110. 平衡二叉树、*257. 二叉树的所有路径、404. 左叶子之和、*222. 完全二叉树的节点个数
  • #渗透测试#SRC漏洞挖掘# 信息收集-Shodan之网页版
  • 面试简历技巧分享
  • threejs开源实例-粒子地球