Scala项目(图书管理系统)
3、service
BookService
package org.app
package service
import 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 service
import dao.UserDAO
import org.app.models.UserModel
class 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)
}
}