I’m trying to understand how Slick works and how to use it… and looking at their examples in GitHub I ended up with this code snippet in MultiDBCakeExample.scala:
trait PictureComponent { this: Profile => //requires a Profile to be mixed in...
import profile.simple._ //...to be able import profile.simple._
object Pictures extends Table[(String, Option[Int])]("PICTURES") {
...
def * = url ~ id
val autoInc = url returning id into { case (url, id) => Picture(url, id) }
def insert(picture: Picture)(implicit session: Session): Picture = {
autoInc.insert(picture.url)
}
}
}
I suppose the * method returns a row in the table, while autoInc should somehow provide functionality for automatically incrementing the entity id… but to be honest I’ve some trouble in understanding this piece of code. What does returning refer to? What does autoInc return?
I looked at the Slick documentation but I was unable to find helpful information. Any help would be really appreciated 😉
Because that
autoInccan be confusing I will provide you a working example (please note that my DB is PostgreSQL so I need that hack withforInsertin order to make Postgresql driver increment auto-inc values).My RichTable is an abstract class in order to not declare ids for each Table I have but just extend this:
and use it like:
Since you pass
Noneforid, it will be generated automatically by PostgreSql driver when Slick inserts this new entity.I have a few weeks since I started with Slick and I really recommend it!
UPDATE: If you want to not use
forInsertprojections, another approach is the following – in my case the entity isAddress.Create sequence for each table on schema creation:
Define a method to generate the ids using sequences (I defined this
onceinRichTableclass:and in the mapper override
insertmethod like:And now, you can pass
Nonewhen you do an insert and this methods will do a nice work for you…