3、service
BookService
package org.app
package serviceimport org.app.dao.{BookDAO, BorrowRecordDAO}
import org.app.models.{BookModel, BorrowRecordModel}import java.time.LocalDateTime
import scala.collection.mutable.ListBuffer// 图书业务逻辑层
class BookService {private val bookDAO = new BookDAO()private val borrowRecordDAO = new BorrowRecordDAO()// 查询所有的图书// def searchBooks(query:String): 图书列表List(Book对象)def searchBooks(query:String):ListBuffer[BookModel] = {// 从文本文件中读取书本信息,并保存列表中,返回val books = bookDAO.loadBooks()query match {case "" => books // 没有条件,就返回全部case _ => books.filter(b => b.name.contains(query) || b.author.contains(query)) // 有条件,就过滤}}// 普通用户,借阅图书def borrowBook(username:String, bookId:Int):Boolean = {// (1)根据图书的ID,查询图书,判断图书是否存在val books = bookDAO.loadBooks()// 所有的借阅记录val records = borrowRecordDAO.loadBorrowRecords()val book = books.find(b => b.id == bookId)if(book.nonEmpty){val b = book.get// (2)判断图书是否已经被借出if(b.available){// (3)借阅图书 更新这本书的状态b.available = false// 把更新之后的图书的信息写回txt文件bookDAO.saveBooks(books)// 添加一条借阅记录records += BorrowRecordModel(username, b.id,b.name, LocalDateTime.now().toString)// 写借阅记录回文件borrowRecordDAO.saveBorrowRecords(records)println("借阅成功,已保存借阅记录!")true} else {println("这本书被借走了")false}} else {println("没有找到这本书")false}}
}
UserService
package org.app
package serviceimport dao.UserDAOimport org.app.models.UserModelclass UserService {private val userDAO= new UserDAO()// 身份校验def authenticateUser(username: String, password: String): Option[UserModel] = {// 去根据用户名和密码查询,是否有符合要求的用户val users = userDAO.loadUsers()users.find(user => user.username == username && user.password == password)}
}