Dealing with Options when inserting data

53 views
Skip to first unread message

Gabriel Raineri

unread,
Oct 31, 2013, 11:42:37 AM10/31/13
to scalikejdbc...@googlegroups.com
Hi everybody!

I'm trying to figure out the best way to deal with optional values when inserting data.

Here's the example:

case class Group(
  id: Option[Long],
  name: String,
  parent: Option[Group]
)

object Groups extends SQLSyntaxSupport[Group] {
  override val tableName = "group"
  override val columnNames = Seq("id", "name", "parent_id")
}

Somewhere in the code:
def insertGroup(group: Group) = DB localTx { implicit s =>
  val g = Groups.column
  val id = withSQL {
    insertInto(Groups)
      .columns(g.name, g.email, g.ownerId, g.parentId)
      .values(group.name, group.email, group.owner.id, <?????????>)
  }.updateAndReturnGeneratedKey().apply()
  group.copy(id = Some(id))
}

The question is, does ScalikeJdbc provide a way to deal with these cases? 

Thanks! 

... and keep it up! This framework is looking great.

Cheers,
G.

Gabriel Raineri

unread,
Oct 31, 2013, 3:06:04 PM10/31/13
to scalikejdbc...@googlegroups.com
I guess this may work:

def insertGroup(group: Group) = DB localTx { implicit s =>
  val g = Groups.column
  val id = withSQL {
    insertInto(Groups)
      .columns(g.name, g.parentId)
      .values(group.namegroup.parent.flatMap(_.id))
  }.updateAndReturnGeneratedKey().apply()
  group.copy(id = Some(id))
}

Is None (always) converted to null? 

Cheers,
G.

Kazuhiro Sera

unread,
Oct 31, 2013, 6:16:36 PM10/31/13
to Gabriel Raineri, scalikejdbc...@googlegroups.com
Hi,

>Is None (always) converted to null?

Yes, that's right.

>... and keep it up! This framework is looking great.

So grad :)

Thanks,
-Kaz
> --
> You received this message because you are subscribed to the Google Groups
> "ScalikeJDBC Users Group" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to scalikejdbc-users...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

y2k-shubham

unread,
Feb 23, 2018, 2:09:45 AM2/23/18
to ScalikeJDBC Users Group
I say this should be added to the docs.
(Is is already there and i missed?)

This is such a simple workaround for an otherwise not-so-trivial, but common problem;
And I had to dig archives to get to this.
Reply all
Reply to author
Forward
0 new messages