Last active
August 29, 2015 14:00
-
-
Save echeipesh/11055138 to your computer and use it in GitHub Desktop.
Slick 2.0 CRUD Trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Unique { | |
val id: String | |
} | |
/** | |
* Abstraction over a standard "Indexed" table. | |
*/ | |
trait CrudComponent{ this: Profile => | |
import profile.simple._ | |
abstract class IndexedTable[T](tag: Tag, name:String) extends Table[T](tag, name){ | |
def id:Column[String] | |
} | |
trait Crud[T <: IndexedTable[A], A <: Unique] { | |
val query: TableQuery[T] | |
def count()(implicit session: Session): Int = query.length.run | |
def all()(implicit session: Session): List[A] = query.list | |
def delete(id: String)(implicit session: Session): Boolean = query.filter(_.id === id).delete > 0 | |
def getById(id: String)(implicit session: Session): Option[A] = queryById(id).firstOption | |
lazy val queryById = for { | |
id <- Parameters[String] | |
e <- query if e.id === id | |
} yield e | |
def insert(entity: A)(implicit session: Session): Boolean = { | |
query.forceInsert(entity) == 1 | |
} | |
def update(entity: A)(implicit session: Session): Boolean = { | |
queryById(entity.id).update(entity) == 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment