5.4. Model Relations

Now let's add a relation to the 'Editor' class. For this let's say that the editor has some asoociated with it. Let's simply create a class names 'Book' and add a field named 'books' of type 'java.util.Set' to the class Editor and a field named 'editor' to the 'Book' class.
public class Editor {
	
	private Set books = new HashSet();

	public Set getBooks() {
		return books;
	}
	
	public void setBooks(Set books) {
		this.books = books;
	}
}
And the class for the books:
public class Book {
	
	private int bookId;
	
	private Editor editor;
	
	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	public Editor getEditor() {
		return editor;
	}

	public void setEditor(Editor editor) {
		this.editor = editor;
	}
}
With this, the table associated to the class 'Book' will look like this:
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| book_id      | int(11)      | NO   | PRI |         | auto_increment |
| editor_id    | int(11)      | YES  | MUL |         |                |
+--------------+--------------+------+-----+---------+----------------+
The table field 'editor_id' represents a foreign key that points to the primary key of the editor table.

Of course, the book must have an author. We'll add an author to the model and with this we will show how to create and use components.