Question

Possible Duplicate:
Is there an easy way to get a Stream as output of a RowParser?

When I have a statement like this when using Anorm in the Play! Framework:

def all(): List[Note] = 
    DB.withConnection { implicit c => SQL("select * from note").as(note *) }

it appears to return a List of my model objects. Can I do this differently so I can get a Stream[Note] instead so it does "lazy" loading of the rows? Or maybe it is already somehow even though it claims to be returning a List.

In other words, if I do all().head I would want it to only have fetched the first row. It appears to me that before the "as" it starts out as a stream, but after "as" it is a List.

Was it helpful?

Solution

I asked a very similar question yesterday, so you might want to check that out. I gave a solution to your problem, but my question was about having a more elegant/concise way to achieve the same.

If you generate a List, there is nothing lazy about it, your whole result is parsed and returned. However, even if you use a Stream, for performance reasons, you should try to reduce the number of rows already in your query. For example, if you are only interested in the first n rows, you should add limit n, otherwise the database will still be queried for all rows, and you will just save a little time by not parsing them when using Stream instead of List.

OTHER TIPS

Check this link http://www.playframework.org/documentation/2.0/ScalaAnorm

You can use the apply() method instead of the as() to get the Stream but then you will have to parse the Note yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top