4

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 :-)

ttt
  • 3,934
  • 8
  • 46
  • 85
  • 2
    I do not think there is any other way to achieve this. What you have done is the correct approach, I believe. Hibernate might be doing a similar way internally. Also, we need to get out of the Hibernate/ORM mindset when using Slick. I had also the same doubt, and proceeded like you have done. – Yadu Krishnan Oct 15 '15 at 07:51
  • Bumped into the same situation and afaics, this is the best way to go about it. Have you tried looking into the query that this transaction translates into? – Ashesh Oct 11 '16 at 15:57

0 Answers0