Search code examples
scalasqueryl

how to implement @MappedSuperClass in squeryl?


I have 12 tables in the database. and all tables has same columns and same relations.

So I had writen the code in JPA.

@MappedSuperclass
public class BaseAddress {
... properties and relations (@ManyToOne / @OneToMany)
}

@Entity
public class Address1 extends BaseAddress {
  // has no code. properties and relations are inherited.
}

@Entity 
public class Address2 extends BaseAddress {
  // has no code. properties and relations are inherited.    
}

but, I don't know how implemented it in squeryl schema definition. How implement that relation inheritance in squeryl ?


Solution

  • Squeryl will reflect on all of the available fields. It doesn't make a distinction on whether they are inherited or not. Something like:

    class BaseAddress(id: Long, address: String)
    
    class Address1(id: Long, address: String) extends BaseAddress(id, address)
    
    class Address2(id: Long, address: String) extends BaseAddress(id, address)
    
    object MySchema extends Schema {
    
      val address1 = table[Address1]
    
      val address2 = table[Address2]
    
    }
    

    Should work similarly to the Hibernate code you posted. For the relationships, with Squeryl they are defined in the Schema object rather than within the model class. You can add a helper method if you're defining the same relation more than once:

    def addressTableWithUserRelation[T <: BaseAddress]: (Table[T], OneToManyRelation[User, T]) = {
      val table = Table[T]
      val relation = oneToManyRelation(users, table)((u,t) => u.id === t.userId)
      (table, relation)
    }
    
    val (address1, address1ToUser) = addressTableWithUserRelation[Address1]