Playframework 关于事务和嵌套数据库写入(使用Scala)

Playframework 关于事务和嵌套数据库写入(使用Scala),playframework,playframework-2.0,playframework-2.1,anorm,Playframework,Playframework 2.0,Playframework 2.1,Anorm,假设我有以下方法: 在网站列表模型上: def create(urls: List[String]) = DB.withTransaction(implicit c => { val websites = urls.map(Website.create(_)) val listId: Option[Long] = SQL("INSERT INTO LIST (created_date, active) VALUES ({created_date}, {active})").

假设我有以下方法:
在网站列表模型上:

def create(urls: List[String]) = DB.withTransaction(implicit c => {
    val websites = urls.map(Website.create(_))
    val listId: Option[Long] = SQL("INSERT INTO LIST (created_date, active) VALUES ({created_date}, {active})").
      on('created_date -> new Date(), 'active -> true).
      executeInsert()
    websites.foreach(websiteId =>
      SQL("INSERT INTO websites_list (list_id, website_id) VALUES ({listId}, {websiteId})").
      on('listId -> listId.get, 'websiteId -> websiteId.id).executeInsert()
    )

    throw new Exception()
  })
在网站模型上:

def create(url: String): Website = DB.withConnection {
    implicit c =>
      val currentDate = new Date()
      val insertedId: Option[Long] = SQL("insert into websites (url, Date_Added) values ({url}, {date})").
        on('url -> url, 'date -> currentDate).
        executeInsert()
      Website(insertedId.get, url, currentDate)
  }
如您所见,我在WebsitesList创建方法上启动了一个事务,并且该方法调用了网站模型的创建方法。
我的目标是,如果由于某种原因无法创建网站列表,则删除已创建的网站记录。为了测试它,我引发了一个异常,正如预期的那样,不会创建WebSiteList和List记录。但是,异常发生后不会回滚网站记录并保留在数据库中

我的理论是,Website.create方法创建了一个新的连接,而不是使用现有的连接。有人知道我该怎么解决这个问题吗


谢谢

您可以更改签名以采用隐式连接,然后在create方法之外控制事务

Website.scala

对象网站{
def create(url:字符串):网站={
DB.withConnection{隐式连接=>
createWithConnection(url)
}
}
def createWithConnection(url:String)(隐式连接:连接):网站={
val currentDate=新日期()
val insertedId:Option[Long]=SQL(“插入到网站(url,Date_添加)值({url},{Date})”)。
在('url->url',日期->当前日期)。
executeInsert()
网站(insertedId.get、url、currentDate)
}
}
WebsiteList.scala

对象网站列表{
def create(url:List[String])=DB.withTransaction(隐式c=>{
createWithConnection(URL)
})
def createWithConnection(URL:List[String])(隐式连接:连接)={
val websites=url.map(Website.createWithConnection)
val listId:Option[Long]=SQL(“插入列表(创建日期,活动)值({created日期},{active})”)。
在('created_date->new date(),'active->true)上。
executeInsert()
websites.foreach(websiteId=>
SQL(“插入网站列表(列表id,网站id)值({listId},{websiteId})”)。
在('listId->listId.get,'websiteId->websiteId.id.)上执行
)
抛出新异常()
}
}
正如您在
网站列表中所看到的
我将
DB.withConnection
更改为
DB.withTransaction
,因为您正在进行多个插入,并希望它们在同一事务中一起提交

这使您可以控制何时何地共享
连接

例如,您可以在控制器中执行事务管理,该控制器更清楚事务应使用多长时间:

对象控制器扩展控制器{
def someAction(someData:String)=操作{隐式请求=>
DB.withTransaction{隐式连接=>
创建(someData)
创建(someData)
}
}
}
对象模型{
def create(数据:字符串)(隐式连接:连接){
}
}
对象模型{
def create(数据:字符串)(隐式连接:连接){
}
}

SQL对象位于何处?连接包是什么?