Play框架Scala应用程序(数据库)中的数据库事务
我正在使用Play框架和scala开发应用程序.我正在将anorm用于数据访问层.我有一个我无法解决的问题.
I am developing an application using Play framework and scala. I am using anorm for data-access layer. And I've got a problem I could not solve.
简介:我希望能够在数据访问对象(dao)中拥有一些方法,以便在事务内部工作以及被单独调用.
Brief: I want to be able to have methods in data-access objects (dao) to work inside transactions as well as being called alone.
详细信息:
我的数据访问层由类组成,这些类仅具有通过数据库执行特定SQL的方法.传统上,它们看起来像:
I have data-access layer consist of class with methods that only executes particular SQL over database. Traditionally they looks like:
def list() = DB.withConnection { implicit cn =>
...
}
现在,我想在事务范围内执行一些方法.类似于传统的选择更新服务方法,但仍然能够单独运行它们.所以,我的想法是这样的:
Now I want to have some methods to be executed in a transaction scope. Like traditional select-update service methods but still be able to run them alone. So, what I have in my mind is like this:
class Service {
def fooTransacted() = {
inTransaction {
val old = dao.select(id = 2)
val newObj = old.copy(isActive = true)
dao.update(newObj)
}
}
def fooSinle() = {
dao.select(id = 2)
}
}
我尝试了几种方法,但无法提出任何解决方案.
I tried around several ways, but could not come up with any solution.
那
class Dao {
def foo(id: Long)(implicit connection: Connection) = {
SQL("select * from foo where id={id}").on('id->id).as(...)
}
}
class Service{
def withConnection = {
DB.withConnection {implicit connection =>
Dao.foo(1)
Dao.foo(2)
}
}
def withTransaction = {
DB.withTransaction {implicit connection =>
Dao.foo(1)
Dao.foo(2)
}
}