Chapter 12
[ 347 ]
Spring Data mapping for MongoDB
In between event requests, we store the latest state of the DSL state variables. These
variables can be any fundamental type or a collection of fundamental type objects.
Basically, anything that can be marshaled into and out of JSON as is. We therefore
need to also have a storage mechanism that allows arbitrary data to be stored.
MongoDB turns out to be a natural fit for this. Mongo is a JSON document store
and is schemaless, meaning that we don't have to describe the structure of the data
we store. Spring also has a powerful set of libraries that allow it to integrate easily
with a Mongo database. This is the entire configuration we need to get working with
Mongo using the Spring Data Mongo libraries. First we declare MongoConfig, which
configures Spring to use the TicTacToe database:
@Configuration
class MongoConfig extends AbstractMongoConfiguration {
@Override
String getDatabaseName() {
"tictactoe"
}
@Override
Mongo mongo() throws Exception {
new MongoClient()
}
}
A MongoDB database can contain multiple JSON document collections. In our case,
we only need one. Here we declare a Spring Data mapping repository for storing the
game sessions. Based on the Spring Boot convention over configuration principles,
this class declaration will automatically make use of a collection called GameSession.
Spring Data also automatically generates the findBySessionId method to query
GameSession objects by sessionId:
interface GameSessionRepository
extends MongoRepository<GameSession, BigInteger> {
GameSession findBySessionId(String sessionId)
}