I have following code like user and userAddress, which is kind of one-to-one or many-to-one relationship.
case class User(id: Long, name: String, addressId: Long)
case class Address(id: Long, street: String)
class UserTable(tag: Tag) extends Table[User](tag, "USERS") {
def id = ???
def name = ???
def addressId = ???
def * = ???
}
class AddressTable(tag: Tag) extends Table[Address](tag, "ADDRESS") {
def id = ???
def street = ???
def * = ???
}
I want to save a user with the address and return the user Id, the code I wrote is like following:
val users = TableQuery[UserTable]
val addresses = TableQuery[AddressTable]
def saveUserWithAddress(user: User, address: Address): Future[Long] = {
val insertion = (for {
a <- (addresses returning addresses.map(_.id)) += address
u <- (users returning users.map(_.id)) += (user.copy(addressId = a))
} yield u).transactionally
db.run(insertion)
}
The reason I want to put transactionally here is I want to save them in one transaction.
Could I ask is that the right way to save an object with relationship? Or are there any short way to do this?? As I am from Hibernate ORM background and it's quite easy to achieve that, just session.save(user)
, that's done.
Please be patient if you think it's too easy to do in another way, as I am new to Scala and Slick :-)