我试图将产品插入我的数据库,但事实上我什么都没插入
我的模型看起来像:
case class Product(id: Option[Int], name: String, description: String, style: String, price: Int, cat_id: Int, size_id: Int, brand_id: Int)
表格定义:
class ProductsTable(tag: Tag) extends Table[Product](tag, "PRODUCTS") {
def id = column[Int]("PRODUCT_ID", O.PrimaryKey, O.AutoInc)
def title = column[String]("NAME")
def description = column[String]("DESCRIPTION")
def style = column[String]("STYLE")
def price = column[Int]("PRICE")
def category_id = column[Int]("CATEGORY_ID")
def size_id = column[Int]("SIZE_ID")
def brand_id = column[Int]("BRAND_ID")
def category = foreignKey("CAT_FK", category_id, cat.Categories)(_.cat_id, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.Cascade)
def size = foreignKey("SIZE_FK", size_id, sizes.Sizes)(_.size_id, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.Cascade)
def brand = foreignKey("BRAND_FK", brand_id, brands.Brands)(_.brand_id, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.Cascade)
def * = (id.?, title, description, style, price, category_id, size_id, brand_id) <>(Product.tupled, Product.unapply _)
}
在DAO中插入方法:
def insert(product: Product): Future[Unit] = db.run(Products += product).map { _ => () }
和控制器:
def newproduct = Action { implicit request =>
val product: models.Product = productForm.bindFromRequest().get
productDAO.insert(product)
Redirect(routes.ProductController.listproducts())
}
答案 0 :(得分:3)
您对从productDAO返回的未来做了什么?由于这是异步调用,因此您启动的线程不会发生任何事情。你必须对未来采取行动,找出发生了什么。如果您的网络库是异步的,您应该能够像这样完成:
def newproduct = Action { implicit request =>
val product: models.Product = productForm.bindFromRequest().get
productDAO.insert(product).andThen {
case Success(_) =>
Redirect(routes.ProductController.listproducts())
case Failure(e) =>
log.error(e) // some logging
Failure(500) // some failure
}
}
如果您的网络库不是异步,您可能需要等待答案:
def newproduct = Action { implicit request =>
val product: models.Product = productForm.bindFromRequest().get
import scala.concurrent.duration._
Try(Await.result(productDAO.insert(product), 10 seconds)) match {
case Success(_) =>
Redirect(routes.ProductController.listproducts())
case Failure(e) =>
log.error(e) // some logging
Failure(500) // some failure
}
}