2014-03-06 70 views
3

我正在使用浮油,並且對浮油會話有疑問。我將首先舉例, 訂單類包含訂單項,訂單可以獲取訂單項或刪除其中一個訂單項,訂單也可以自行定價。下面是僞代碼:如何使用共享會話進行多個數據庫操作?

Order類{

def getLineItems= database withSesison{ 
     //get Line Items from db repository 
    } 

    def removeLineItem(itemId: String) = database withTransaction{ 
     implicit ss: Session => 
     //Remove item from db 
     //Price the order 
    } 

    def priceOrder() = database withTransaction{ 
     implicit ss: Session => 
     //getLineItems 
     //recalculate order price by each line item 
    } 
} 

所以,當我試圖刪除訂單項,它會創建一個新的會話和交易,然後它會調用priceOrder,這也將創造一個新的會話和事務,priceOrder將調用getLineItems,這會創建另一個新會話。

從光滑的文檔中,我知道每個會話都打開一個jdbc連接,所以在一個方法調用中它會創建3個數據庫連接,這是浪費連接資源。有沒有辦法只使用一個連接來完成這個操作?

我知道浮油有一個threadLocalSession,它將會話綁定到本地線程,但從https://groups.google.com/forum/#!topic/scalaquery/Sg42HDEK34Q我看我們應該避免使用threadLocalSession。

請幫忙,謝謝。

回答

0

您可以使用currying傳遞隱式會話,而不是爲每個方法創建新的會話/事務。

def create(user: User)(implicit session: Session) = { 
    val id = Users.returning(Users.map(_.id)).insert(user) 
    user.copy(id = Some(id)) 
} 

然後,控制器或某個地方,當你想調用的方法,您設置一個會話/交易,將被用於該塊內的所有數據庫工作。

// Create the user. 
DB.withTransaction { implicit session: Session => 
    Users.create(user) 
} 

隱式會話是如何設置一些Slick示例。 https://github.com/slick/slick-examples/blob/master/src/main/scala/com/typesafe/slick/examples/lifted/MultiDBCakeExample.scala

+0

謝謝Rob,你說得對。但是有時候我不想在外面圍繞會話,因爲我可能會在UI層或其他地方調用像getLineItems這樣的方法,所以我需要在那個方便的實體對象中使用會話。 – Simon

相關問題