Scala Slick and nested case classes

旧街凉风 提交于 2020-01-14 04:21:07

问题


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:


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.



来源:https://stackoverflow.com/questions/52804348/scala-slick-and-nested-case-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!