Question

I'm using Spray with Slick. Spray is actually very easy to use, and the same goes with Slick. However, the infamous Slick way to connect to Database is like:

  Database.forURL("jdbc:mysql://localhost:3306/SprayBlog?characterEncoding=UTF-8", user="xxxx", password="xxx", driver = "com.mysql.jdbc.Driver") withSession {
    implicit session =>

      (Article.articles.ddl ++ User.users.ddl).create
  }

I hate typing this much whenever I do a database connection. I have used Play-Slick framework before, and Play has this application.conf, with which I can store my database connection address, username and password. I don't know if this is true, but shouldn't people store their database info on an encrypted file, and I may be wrong but I feel conf is blocked from outside access and encrypted.

So is there a way for me to call database manipulations easier?? If I do want to put the info in the conf, how can I access it?

Was it helpful?

Solution

store your db in a val or write a def that abstracts over what you feel is repetitive. withSession is good for connection scoping. I don't know spray conf files, but they may use Typesafe config, which is a library that allows to read the file. Spray probably also exposes its config through an api.

OTHER TIPS

With Slick 2.1.0 you can use Database.forConfig().

In application.conf:

db {
    url = "jdbc:mysql://localhost/DatabaseName"
    driver = "com.mysql.jdbc.Driver"
    user = "root"
    password = ""
}

In your database access code:

import scala.slick.driver.MySQLDriver.simple._
import models.Item
import tables.ItemTable

class ItemService {

  val items = TableQuery[ItemTable]

  def all: List[Item] = Database.forConfig("db") withSession { implicit session: Session =>
    items.list
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top