【问题标题】:Avoiding Squeryl transaction in Play! controllers在 Play 中避免 Squeryl 交易!控制器
【发布时间】:2012-08-03 02:37:53
【问题描述】:

我正在学习玩!我关注了To do List tutorial。现在,我想用 Squeryl 代替 Anorm,所以我尝试翻译教程,并且确实有效。

不过,还有一件小事让我很恼火。这是我模型的相关部分

def all: Iterable[Task] = from(tasks) {s => select(s)}

以及控制器中对应的action列出所有任务

def tasks = Action {
    inTransaction {
        Ok(views.html.index(Task.all, taskForm))
    }
}

视图包含,例如

<h1>@tasks.size task(s)</h1>

我不喜欢的是,与更新或删除任务的方法不同,我必须在控制器操作中管理事务。

如果我将inTransaction 移动到all 方法,我会得到一个异常,

[RuntimeException: No session is bound to current thread, a session must be created via Session.create and bound to the thread via 'work' or 'bindToCurrentThread' Usually this error occurs when a statement is executed outside of a transaction/inTrasaction block] 

因为视图试图获取tasks的大小,但此时事务已经关闭。

有没有办法只在模型中使用 Squeryl 事务而不将这些细节暴露给控制器级别?

【问题讨论】:

  • 为什么不直接将 Iterable 转换为模型中的 List 呢?

标签: scala playframework squeryl


【解决方案1】:

嗯。这是因为对 Iterable 的惰性评估需要会话绑定(size() 方法)。 如果您将 Iterable 转换为 List 或 Vector (IndexedSeq) 我想这可能会起作用。

from(tasks)(s => select(s)).toIndexedSeq //or .toList

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-06-16
  • 2011-01-05
  • 2021-04-12
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
相关资源
最近更新 更多