0

データベース トランザクションを実行します。

def create(model: Model, orderNum: String) = {
  db.handle withSession { implicit ss: Session=>
    ss.withTransaction { // auto commit now set to false
      val result = for {
        uid <- repo.user.create(model)
        mid <- repo.membership.create(uid)
        oid <- repo.orders.create(model, uid, orderNum)
      } yield uid
      result fold( 
        e=> { ss.rollback; Left(e) }, 
        s=> { Cache.remove("member.directory"); Right(s) } 
      )
    }
  } 
}

リポジトリのユーザー作成実装が暗黙的なセッションを取る場合、それは上記の withTransaction が有効なセッションと同じセッションですか、それとも暗黙的な値は「is the」ではなく「is a」ですか?

def create[T <: User](t: T)(implicit ss: Session) = // what Session is this?
  for {
    uid <- either( Users.insert( Users(t) ), i18n("user not created") )
    ur  <- either( UserRoles.insert( UserRole(uid, t.role) ), i18n("user role not created") )
  } yield uid

セッションを明示的に渡し、repo.user.create(model)(ss)明示的なセッションを作成することもできますが、より簡潔で便利な暗黙のアプローチが同じ結果、トランザクション対応セッションを提供するかどうかを知りたいです

4

2 に答える 2

1

私があなたを正しく理解していれば、あなたは ScalaQuery を使用しており、ユーザーが外部からセッションを提供するときにもメソッドを機能させたいと考えています。

def withSession [T] (f: ⇒ T): T 提供されたサンクを新しいセッションで実行し、最後にセッションを自動的に閉じます。

def withSession [T] (f: (Session) ⇒ T): T 提供された関数を新しいセッションで実行し、最後にセッションを自動的に閉じます。

これらはどちらも新しいトランザクションを作成しているため、Optional[Session] を暗黙的に使用し、デフォルトで None に設定する方法です。

  def onProvidedOrCreatedSession[K](f: Session => K)(session:Option[Session]) = {
    session match {
      case Some(s) => f(s)
      case None => db.withSession { f }
    }
  }

  def create(model: Model, orderNum: String)(implicit session:Option[Session]=None){
    onProvidedOrCreatedSession( 
      implicit s => s.withTransaction {  val x = 10 }
    )(session)  
     
  }
于 2012-08-03T15:12:01.357 に答える
0

以下があなたがやろうとしていることの忠実な抽象化であるかどうかはわかりませんが、役に立てば幸いです:

class Store(var x: Int) {
  def flip() { x = -x }
}

object M1 {
  implicit val store2 = new Store(2)

  def create(s: String) = {
    implicit val store3 = new Store(3)

    { implicit store: Store => 
        println("[M1.create] store.x = " + store.x)
        store.flip()
        M2.create("tummy")
        println("[M1.create] store.x = " + store.x)
    }
  }
}

object M2 {
  implicit val store4 = new Store(4)

  def create(s: String)(implicit store: Store) = {
    println("[M2.create] store.x = " + store.x)
    store.flip()
  }
}

M1.create("dummy")(new Store(1))

出力は次のとおりです。

[M1.create] store.x = 1
[M2.create] store.x = -1
[M1.create] store.x = 1
  • new Store(1)明示的に渡されM1.createM2.create

  • 追加の暗黙のストアstore2, store3, store4は、明らかにコンパイラによって無視されます。

于 2012-08-03T13:25:51.630 に答える