2016-09-04 3 views
0

Ich arbeite in einem Projekt mit Scala Play 2 Framework, wo ich Slick als FRM und Postgres Datenbank verwende.Wie erstellt man Entity-Beziehungen in Slick?

In meinem Projekt ist Kunde eine Entität. Also erstelle ich auch eine Kunden-Tabelle und eine Kunden-Fall-Klasse und ein Objekt. Eine andere Entität ist ein Konto. Der Code wird unten gegeben

case class Customer(id: Option[Int], 
       status: String, 
       balance: Double, 
       payable: Double, 
       created: Option[Instant], 
       updated: Option[Instant]) extends GenericEntity { 
    def this(status: String, 
     balance: Double, 
     payable: Double) = this(None, status, balance, payable, None, None) 
} 


class CustomerTable(tag: Tag) extends GenericTable[Customer](tag, "customer"){ 
    override def id = column[Option[Int]]("id") 
    def status = column[String]("status") 
    def balance = column[Double]("balance") 
    def payable = column[Double]("payable") 
    def account = foreignKey("fk_customer_account", id, Accounts.table)(_.id, onUpdate = ForeignKeyAction.Restrict, onDelete = ForeignKeyAction.Cascade) 

    def * = (id, status, balance, payable, created, updated) <> ((Customer.apply _).tupled, Customer.unapply) 
} 

object Customers extends GenericService[Customer, CustomerTable] { 
    override val table = TableQuery[CustomerTable] 
    val accountTable = TableQuery[AccountTable] 
    override def copyEntityFields(entity: Customer, id: Option[Int], 
    created: Option[Instant], updated: Option[Instant]): Customer = { 
     entity.copy(id = id, created = created, updated = updated) 
    } 
} 

Jetzt ist das Problem, wie kann ich ein Kontoobjekt innerhalb des Kundenobjekts erstellen? Oder wie kann ich das Konto eines Kunden bekommen?

Antwort

2

Slick ist nicht ORM es ist nur eine funktionale relationale Mapper. Verschachtelte Objekte können nicht direkt in slick wie Hibernate oder anderen ORMs Statt

Slick

//Usual ORM mapping works with nested objects 
case class Person(name: String, age: Int, address: Address) //nested object 

//With Slick 
case class Address(addressStr: String, id: Long) //id primary key 
case class Person(name: String, age: Int, addressId: Long) //addressId is the id of the address object and its going to the foreign key 

Konto Objekt in Kunden

case class Account(id: Long, ....) // .... means other fields. 
case class Customer(accountId: Long, ....) 

Platz accountId innerhalb des Customer Objekts verwendet werden und mach es fremd Schlüssel

Für weitere Informationen zu Slick Beispiel als Teil der Dokumentation verweisen