Scala Slick and nested case classes

2019-06-06 05:46发布

I'm quite new to Scala and need to use slick to build a table mapping for these case classes.

I can do it for a simple case class but the nesting and option parameters are leaving me confused how to do this?

case class Info(fullName: Option[String], dn: Option[String], manager: Option[String], title: Option[String], group: Option[String], sid: Option[String])

case class User(username: String, RiskScore: Float, averageRiskScore: Float, lastSessionId: String, lastActivityTime: Long, info: Info)

I need to end up with a simple table which contains all of the combined parameters.

1条回答
叼着烟拽天下
2楼-- · 2019-06-06 06:00

Given your nested case class definitions, a bidirectional mapping for the * projection similar to the following should work:

case class Info(fullName: Option[String], dn: Option[String], manager: Option[String], title: Option[String], group: Option[String], sid: Option[String])

case class User(username: String, riskScore: Float, averageRiskScore: Float, lastSessionId: String, lastActivityTime: Long, info: Info)

class Users(tag: Tag) extends Table[User](tag, "USERS") {

  def username = column[String]("user_name")
  def riskScore = column[Float]("risk_score")
  def averageRiskScore = column[Float]("average_risk_score")
  def lastSessionId = column[String]("last_session_id")
  def lastActivityTime = column[Long]("last_acitivity_time")

  def fullName = column[Option[String]]("full_name", O.Default(None))
  def dn = column[Option[String]]("dn", O.Default(None))
  def manager = column[Option[String]]("manager", O.Default(None))
  def title = column[Option[String]]("title", O.Default(None))
  def group = column[Option[String]]("group", O.Default(None))
  def sid = column[Option[String]]("sid", O.Default(None))

  def * = (
      username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, (
        fullName, dn, manager, title, group, sid
      )
    ).shaped <> (
      { case (username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, info) =>
          User(username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, Info.tupled.apply(info))
      },
      { u: User =>
          def f(i: Info) = Info.unapply(i).get
          Some((u.username, u.riskScore, u.averageRiskScore, u.lastSessionId, u.lastActivityTime, f(u.info)))
      }
    )
}

Here is a great relevant Slick article you might find useful.

查看更多
登录 后发表回答