Frage

Is it possible to load a collection lazy with Sala?

e.g. I have an object like

Example 1 (in this case, the whole user list is loaded when retrieving the object)

case class Test(
    @Key("_id") _id: ObjectId = new ObjectId,
    name: String,
    users: List[User]) {
}

or Example 2 (the object is loaded without the list, but no idea how to get the users list)

case class Test(
    @Key("_id") _id: ObjectId = new ObjectId,
    name: String) {
    @Persist val users: List[User] = List()
}

How can I load the object in the first example without the users list? or: How can I load the users list in the second example?

Thanks in advance!

War es hilfreich?

Lösung

Salat author here.

Salat doesn't have anything like ORM lazy loading. The @Persist annotation is meant to persist fields outside of the constructor, but suppresses deserialization because only fields in the constructor will be deserialized.

But you can easily decide when making the query whether you want the list of users or not.

case class Test(@Key("_id") id = new ObjectId, name: String, users: List[User] = Nil) 

You can persist the users as embedded documents inside the test document, and then use the second argument of the query, the ref, to exclude (0) or include (1) fields in the object.

TestDAO.find(/* query */, MongoDBObject("users" -> 0))

The other strategy is to break out user documents into a child collection - see https://github.com/novus/salat/wiki/ChildCollection for more information. In this example, Test is the "parent" and User is the "child".

The strategy there is that in the parent DAO, when saving, you override the save methods to save users using the child DAO, and then save the parent object with users set to Nil.

Then, by default, a Test instance is retrieved with users set to Nil.

If you want to retrieve Test with users, you will need to add a find method to your DAO that manually:

  1. find the test document
  2. use the _id field of the test document to query for user documents by parent id - this will yield List[User]
  3. deserialize the test document to an instance of Test using grater[Test] and copy it with the list of users
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top