2017.03.21 eBean Kotlin simplest ManyToMany association - GlenKPeterson/One-off_Examples GitHub Wiki

Here is an example of a many-to-many mapping using eBean and Kotlin. The idea is that an author can write many books and a book can have many authors. This requires 3 database tables:

  • author stores authors
  • book stores books
  • book_author associates books with authors (many-to-many mapping table).

It only requires 2 Kotlin classes (BaseModel just adds a surrogate key). Examples are tested with Kotlin 1.1.0 and eBean 8.2.1.

Kotlin

// Puts an ID field (surrogate key) on tables that extend this.
@MappedSuperclass
abstract class BaseModel {
    @Id var id:Long = 0
}

@Entity
class Author(@Column var name: String): BaseModel() {
    @ManyToMany(mappedBy = "authors")
    val books:MutableList<Book> = mutableListOf()
}

@Entity
class Book(@Column var title:String) : BaseModel() {
    @ManyToMany // *NOT* (mappedBy = "book") - only map one direction.
    val authors:MutableList<Author> = mutableListOf()
}

Unlike other mappings, you don't need to create or reference a BookAuthor class in Kotlin. You can (and should) make a BookAuthor class if additional fields would belong on such a class. But for pure many-to-many mapping tables, it's a very convenient shorthand to be able to say myBook.authors() and someAuthor.books().

Note that you only add the (mappedBy= to one side of the mapping. The join table name puts the mappedBy side second (if you put mappedBy on Author, the table is called book_author. If on Book, it's called author_book).

To save a book/author relationship:

myAuthor.books.add(someBook)
ebeanServer.save(myAuthor)

Generated (My)SQL

create table author (
  id                            bigint auto_increment not null,
  name                          varchar(255),
  constraint pk_author primary key (id)
);

create table book (
  id                            bigint auto_increment not null,
  title                         varchar(255),
  constraint pk_book primary key (id)
);

create table book_author (
  book_id                       bigint not null,
  author_id                     bigint not null,
  constraint pk_book_author primary key (book_id,author_id)
);
⚠️ **GitHub.com Fallback** ⚠️