Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let's say you have the following case class and Slick table:</p> <pre><code>case class User(id: Option[Int], first: String, last: String) object Users extends Table[User]("users") { def id = column[Int]("id", O.PrimaryKey, O.AutoInc) def first = column[String]("first") def last = column[String]("last") def * = id.? ~ first ~ last &lt;&gt; (User, User.unapply _) } </code></pre> <p>The important things to consider here is the fact that User.id is an Option, because when we create it we will set it to None and the DB will generate the number for it.</p> <p>Now you need to define a new insert mapping which omits the autoincremented column. This is needed because some databases don't allow you to insert into a column which is labeled as Auto Incremental. So instead of:</p> <pre><code>INSERT INTO users VALUES (NULL, "first, "last") </code></pre> <p>Slick will generate:</p> <pre><code>INSERT INTO user(first, last) VALUES ("first", "last") </code></pre> <p>The mapping looks like this (which must be placed inside Users):</p> <pre><code>def forInsert = first ~ last &lt;&gt; ({ t =&gt; User(None, t._1, t._2)}, { (u: User) =&gt; Some((u.first, u.last))}) </code></pre> <p>Finally getting the auto-generated id is simple. We only need to specify in the returning the id column:</p> <pre><code>val userId = Users.forInsert returning Users.id insert User(None, "First", "Last") </code></pre> <p>Or you could instead move the returning statement:</p> <pre><code>def forInsert = first ~ last &lt;&gt; ({ t =&gt; User(None, t._1, t._2)}, { (u: User) =&gt; Some((u.first, u.last))}) returning id </code></pre> <p>And simplify your insert calls:</p> <pre><code>val userId = Users.forInsert insert User(None, "First", "Last") </code></pre> <p><a href="http://slick.typesafe.com/doc/1.0.0/lifted-embedding.html#inserting" rel="nofollow">Source</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload