将squeryl Query转换为case类scala

时间:2014-04-29 03:34:23

标签: scala casting squeryl

我是Squeryl的新手,并试图弄清楚如何将我从查询中返回的结果转换为案例类。我有类似的东西

def getUsers = {
    val data = getUserData
    ...
}

def getUserData = {
    transaction {
        from(users)(s =>
            select(s.id, s.firstName, s.lastName, s.userName, s.email, s.lastLoginDate, s.dateJoined)
        )
    }
}

case class UserData(userId: Long, firstName: String, lastName: String, userName: String, email: String, lastLoginDate: Timestamp, dateJoined: Timestamp)

case class UserDataRecords(users: List[UserData])

理想情况下,我想从UserDataRecords中获取数据。现在它以Query [Tuple7]的形式返回。如

... 
(5,Suzie,Queue,squeue,SQueue@example.com,2014-01-15 22:02:12.0,2014-01-15 22:02:12.0)
...

我无法弄清楚如何投射这些数据。对此的任何帮助都会很棒!

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用map转换结果列表。类似下面的例子应该是一个起点:

def getUserData = {
    transaction {
        from(users)(s =>
            select(s.id, s.firstName, s.lastName, s.userName, s.email, s.lastLoginDate, s.dateJoined)
        ).toList.map { row =>
            UserData(row._1, row._2, row._3, row._4, row._5, row._6, row._7)
        }
    }
}

这将遍历每一行并从元组中创建一个UserData对象,并留下List[UserData]

也就是说,如果您的架构users的类型为Table[UserData],那么您可以这样做:

from(users)(s => select(s))