0

I want to read elements from the database and return them as JSON objects.

Scalatra is set up to return JSON. Databaseschema is created. Players are added.

The following code seems to be the main problem:

get("/") {
  inTransaction {
    List(from(MassTournamentSchema.players)(s => select(s)))
  }
}

I get the following error: "No session is bound to current thread, a session must be created via Session.create and bound to the thread via 'work' or 'bindToCurrentThread' Usually this error occurs when a statement is executed outside of a transaction/inTrasaction block "

I want to do it right so simply adding something like "Session.create" may not really be the right way.

Can anyone help a scalatra-noob? :-)

eventhorizon
  • 2,977
  • 8
  • 33
  • 57
  • I think, the problem relies in my setup. I followed the instructions on the scalatra site do get JSON as standard output. My code returns the newly created List. BUT: [http://squeryl.org/selects.html](http://squeryl.org/selects.html) "[...] the query is sent to the database only when starting iteration, or in other words, when Iterable.iterator is called. [...]" This may happen automatically (configured scalatra to return JSON), but in my case outside of the "inTransaction {...}" block - and eventually also outside of the thread (?). Does anyone have an idea? – eventhorizon Oct 18 '14 at 08:29

1 Answers1

1

I think that your comment is on the right track. The inTransaction block will bind a JDBC connection to a thread local variable and start the connection on it. If the select doesn't occur on the same thread, you'll see an error like the one your received. There are two things I would suggest that you try:

Start your transaction later

List(inTransaction {
  from(MassTournamentSchema.players)(s => select(s))
})

I'm not familiar with Scalatra's List, but it's possible that it's accepting a by-name parameter and executing it later on a different thread.

Force an eager evaluation of the query

inTransaction {
  List(from(MassTournamentSchema.players)(s => select(s)).toList)
}

Here the .toList call will turn the Query object Squeryl returns into a Scala List immediately and guard against any lazy evaluation errors caused by later iteration.

Community
  • 1
  • 1
Dave Whittaker
  • 3,102
  • 13
  • 14