|
| 1 | +# Features - Relationships |
| 2 | + |
| 3 | +## Info |
| 4 | + |
| 5 | +Normal Relationship handling is the use of [embedded documents](https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-one-relationships-between-documents/). |
| 6 | +However, sometimes there is a need for [relationsips beetween collections](https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/). There is a Relations Trait to be used in case classes for easy relationship handling. |
| 7 | + |
| 8 | +## Relations trait |
| 9 | + |
| 10 | +The Relations trait extends DAO case classes with relationship functions. |
| 11 | + |
| 12 | +* relatedRecordForOneToOne (OneToOneRelationship and reference vlue needed) |
| 13 | +* relatedRecordsForOneToMany (OneToManyRelationship and reference vlue needed) |
| 14 | + |
| 15 | +## Demo |
| 16 | + |
| 17 | +Simple Setup. |
| 18 | + |
| 19 | +* User Collection(should have one login and multiple friends) |
| 20 | +* Login Collection |
| 21 | +* Friend Collection |
| 22 | + |
| 23 | +```scala |
| 24 | + |
| 25 | + case class User(id: Long, name: String, loginId: String) |
| 26 | + case class Login(id: String, email: String, password: String) |
| 27 | + case class Friend(id: Long, name: String, userId: Long) |
| 28 | + |
| 29 | + object UserDAO extends MongoDAO[User](database, "user") |
| 30 | + object LoginDAO extends MongoDAO[Login](database, "login") |
| 31 | + object FriendDAO extends MongoDAO[Friend](database, "friend") |
| 32 | + |
| 33 | +``` |
| 34 | + |
| 35 | +For relationship setup we create two Relationships in the UserDAO. |
| 36 | + |
| 37 | +* OneToOne loginRelation (LoginDAO, key is id in user collection) |
| 38 | +* OneToMany friendsRelation (FriendDAO, key is userId in friend collection) |
| 39 | + |
| 40 | +@@snip [RestaurantDatabase.scala](../../../test/scala/com/sfxcode/nosql/mongo/relation/RelationDemoDatabase.scala) { #user_dao } |
| 41 | + |
| 42 | + |
| 43 | +We extend the User case class with the Relations trait and add relation specific functions. |
| 44 | + |
| 45 | +* login (create an Option of Login) |
| 46 | +* friends (create a List of Friend) |
| 47 | + |
| 48 | +@@snip [RestaurantDatabase.scala](../../../test/scala/com/sfxcode/nosql/mongo/relation/RelationDemoDatabase.scala) { #user_class } |
| 49 | + |
| 50 | + |
0 commit comments