scala - How to make use of a shared session for multiple database operation in slick? -
i'm using slick, , have question slick session. i'll give example first, order class contains line items, order can either fetch line items or remove 1 of line item, , order can price self. below pseudocode:
class order{
def getlineitems= database withsesison{ //get line items db repository } def removelineitem(itemid: string) = database withtransaction{ implicit ss: session => //remove item db //price order } def priceorder() = database withtransaction{ implicit ss: session => //getlineitems //recalculate order price each line item } }
so when try remove line item, create new session , transaction, , invoke priceorder, create new session , transaction, priceorder invoke getlineitems, create new session.
from slick document, know each session opening jdbc connection, in 1 method invocation create 3 database connection, it's waste of connection resource. there way use 1 connection finish operation?
i know slick has threadlocalsession bound session thread local, https://groups.google.com/forum/#!topic/scalaquery/sg42hdek34q see should avoid use threadlocalsession.
please help, thanks.
instead of creating new session/transaction each method, can use currying pass implicit session.
def create(user: user)(implicit session: session) = { val id = users.returning(users.map(_.id)).insert(user) user.copy(id = some(id)) }
then, in controller or place, when want call methods, setup session/transaction , used database work within block.
// create user. db.withtransaction { implicit session: session => users.create(user) }
implicit sessions how of slick examples setup. https://github.com/slick/slick-examples/blob/master/src/main/scala/com/typesafe/slick/examples/lifted/multidbcakeexample.scala
Comments
Post a Comment