There are occasions where an entity should map to itself. I.e. consider a Person who has friends. Those friends are instances of Person too:
case class Person(val name: String, val friends: Set[Person])
The table might look like this (ddl for postgresql):
create table Person (
id serial not null,
name varchar(100) not null,
friend_id int,
primary key (id),
foreign key (friend_id) references Person(id) on delete cascade
)
The friend_id
is a foreign key to the same table.
We will map this as a one-to-many relationship between Person and Person:
object PersonEntity extends Entity[Int,SurrogateIntId, Person] {
val aid = key("id") autogenerated (_.id)
val name = column("name") to (_.name)
val friends = onetomany(PersonEntity) foreignkey "friend_id" to (_.friends)
def constructor(implicit m) = new Person(name, friends) with Stored {
val id:Int = aid
}
}
The interesting bit is the following:
val friends = onetomany(PersonEntity) foreignkey "friend_id" to (_.friends)
We created a one-to-many relationship from Person=>Person using the friend_id
column.