-
Notifications
You must be signed in to change notification settings - Fork 12
Queries
Queries are typically constructed with for-comprehensions. The simple SQL query SELECT id, last FROM users WHERE first = 'Stefan'
becomes:
val q1 = for(u <- Users if u.first === "Stefan") yield u.id ~ u.last
Note the use of “===” instead of the usual “==” operator. “Not equal” uses the “=!=” operator instead of “!=”. Alternatively, you can use the methods is
and isNot
.
Implicit joins can be created with multiple generators:
val q4c = for {
u <- Users
o <- Orders if o.userID is u.id
} yield u.first ~ o.orderID
Note that these are just queries, they can be built outside of a Session
and do not touch the database until they are invoked by an Invoker
. You do not need to fiddle with Invokers by hand, there is an implicit conversion. Here are some of the most useful operations implicit invokers supply:
db withSession {
val list:List[(Int,String)] = q1.list //list of (id,last) tuples
val first:(Int,String) = q1.first //(id,last) tuple of first result
val res = q1.mapResult(f) //map function, f must be of type (Int,String)=>T in this case
}
There is also a foreach method defined, so you can use the result of the query in a for loop directly,
but in this case, you need a Session
.
db withSession {
for((id,last) <- q1) println("id: "+id+", last: "+last)
}
Of course, you could have printed the results without storing the query first in q1:
db withSession {
for(u <- Users if u.first === "Stefan") println("id: "+u._1+", last: "+u._3)
}