“权利"是指在Play框架中使用编写Slick 3.0 Scala查询的方法 [英] The "right" way to use write Slick 3.0 Scala queries in Play Framework

查看:156
本文介绍了“权利"是指在Play框架中使用编写Slick 3.0 Scala查询的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Slick 3.0,(当然)几乎所有示例都涵盖了Slick2.x.事情发生了变化,坦率地说,似乎更多变得复杂,而不是更少.

I'm using Slick 3.0 and (of course) almost all the examples out there cover Slick 2.x. Things have changed and frankly seem more complicated, not less.

这里是一个示例:我想通过id获取一个对象(GPPerson).这就是我现在所拥有的,似乎非常冗长...比Slick 2.x更是如此:

Here's an example: I want to get an object (a GPPerson) by id. This is what I have right now, and it seems very verbose... more so than Slick 2.x:

def get(id: GPID): Option[GPPerson] = Await.result(
    db.run(
        people.filter(_.id === id).result), Duration.Inf
    ).headOption

在Slick 2.x中,由于包含隐式内容,因此事情变得更容易.但以上似乎是我想出的最简洁的表达方式.

In Slick 2.x things were easier because of the implicits, among other things. But the above seems to be the most concise expression I've come up with.

它也没有真正解决异常处理,这是我需要添加的.

It also doesn't really address exception handling, which I would need to add.

推荐答案

几个月前,我开始在一个新项目中使用Slick 3.0,但我也有同样的问题.这是我的理解:

I started to use Slick 3.0 in a new project a few months ago and I had the same questions. This is what I understood:

Slick 3.0是为非阻塞异步(反应性)应用程序设计的.显然,这意味着如今的Akka + Play/Spray.在这个世界上,您主要与Future互动,这就是Slick的 db.run 返回Future的原因.使用Await.result没有意义-如果您需要阻止调用,最好返回2.x.

Slick 3.0 was designed for non-blocking asynchronous (reactive) applications. Obviously it means Akka + Play / Spray nowadays. In this world you mostly interact with Futures, that's why Slick's db.run returns Future. There is no point in using Await.result - if you need blocking calls it's better to return to 2.x.

但是,如果您使用反应堆,您会立即受益.例如,Spray是完全无阻塞的库,可以很好地使用 onComplete 指令.您可以调用一种方法,该方法在Spray路线中返回带有Slick的结果的Future,然后将该结果与onComplete一起使用.在这种情况下,整个响应-答复管道都是非阻塞的.

But if you use reactive stack you'll get benefits immediately. For example, Spray is completely non-blocking library that works with Futures nicely using onComplete directive. You can call a method that returns Future with a result from Slick in a Spray route and then use that result together with onComplete. In this case the whole response-reply pipeline is non-blocking.

您还提到了异常处理,因此这正是使用Futures的方法.

You also mentioned exception handling, so this is exactly how you do it - using Futures.

因此,根据我的经验,我将通过以下方式编写您的方法:

So based on my experience I would write your method in a following way:

def get(id: GPID): Future[Option[GPPerson]] = db.run(
  people.filter(_.id === id).result.map(_.headOption)
)

,然后与Future一起使用.

and then work with a Future.

这篇关于“权利"是指在Play框架中使用编写Slick 3.0 Scala查询的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆