2
votes

I'm trying to insert a product to my db, but in fact I insert nothing

My model looks like:

case class Product(id: Option[Int], name: String, description: String,  style: String, price: Int, cat_id: Int, size_id: Int, brand_id: Int)

The table definition:

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 _)
}

Insert method in DAO:

def insert(product: Product): Future[Unit] = db.run(Products += product).map { _ => () }

and Controller:

def newproduct = Action { implicit request =>
  val product: models.Product = productForm.bindFromRequest().get
  productDAO.insert(product)
  Redirect(routes.ProductController.listproducts())
}
1

1 Answers

3
votes

What do you do with the future you get returned from the productDAO? Since this is async calling, nothing will happen on the thread you're initiating from. You must do some action with the future to find out what happened to it. If your web library is async you should be able to finish like this:

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
  }
}

If your web library isn't async you may need to wait for the answer:

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
  }
}