简体   繁体   English

如何重用scala的“ withSession {隐式会话:Session =>”代码块

[英]How to reuse scala slick “withSession { implicit session: Session =>” code block

I have this code in scala using slick 我在scala使用slick代码

def insertTask(task: Task) = {
  conn.dbObject withSession { implicit session: Session =>
    tasks.insert(task)
  }
}

it looks working :) 它看起来工作正常:)

Now I'm going to have also code for readTask and I do not want to duplicate the code for withSession { implicit... 现在,我还将具有readTask代码,并且我不想重复withSession { implicit...

So I thought of doing this: 所以我想这样做:

def doWithConn(dbConn: DBConnection, doThisCodeBlock: => Unit)(implicit session: Session) = {
  dbConn.dbObject withSession { implicit session: Session =>
    doThisCodeBlock
  }
}

and now my code looks like 现在我的代码看起来像

def insertTask(task: Task) = {
  doWithConn(conn, tasks.insert(task)) // here i get the following complication error
}

however I get the following compilation error: 但是我得到以下编译错误:

Error:(36, 34) could not find implicit value for parameter session: scala.slick.jdbc.JdbcBackend#SessionDef doWithConn(conn, tasks.insert(task)) ^ 错误:(36,34)找不到参数会话的隐式值:scala.slick.jdbc.JdbcBackend#SessionDef doWithConn(conn,task.insert(task))^

I'm not sure how to pass the session from the insertTask method. 我不确定如何通过insertTask方法传递session How can I pass it and fix this compilation error? 我如何通过它并解决此编译错误?

thanks 谢谢

withSession is a method that takes a function from session to whatever as an argument. withSession是一种将函数从会话传递到任何参数的方法。 The syntax { implicit session => } is just to make the session implicit. syntax { implicit session => }仅用于使会话隐式。 But you can also just pass a function: 但是您也可以只传递一个函数:

val yourBlock: Session => ... = ...

db.withSession(yourBlock)

No need to wrap it, just use it as is :). 无需包装它,只需按原样使用它即可:)。

Chris 克里斯

The problem I think is your doThisCodeBlock doesn't have a notion of a session being passed to it. 我认为问题是您的doThisCodeBlock没有将会话传递给它的概念。 I think a better way is to simply use currying for reusing statements that use the session: 我认为更好的方法是简单地使用curring重用使用会话的语句:

def insertTaskStatement(task: Task)(implicit session: Session) = {
    tasks.insert(task)
}

def insertOtherThingStatement(otherThing: OtherThing)(implicit session: Session) = {
    things.insert(otherThing)
}

def insertTaskAndOtherThing(task: Task,otherThing: OtherThing) = {
  conn.dbObject withSession { implicit session: Session =>
    insertTaskStatement(task)
    insertOtherThingStatement(otherThing)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM