Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active July 19, 2017 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thjanssen/13be1b3b1969c7ab95c9a6e5cc785f09 to your computer and use it in GitHub Desktop.
Save thjanssen/13be1b3b1969c7ab95c9a6e5cc785f09 to your computer and use it in GitHub Desktop.
Book b = em.find(Book.class, 1L);
Author a = new Author();
a.setFirstName("Thorben");
a.setLastName("Janssen");
a.getBooks().add(b);
b.getAuthors().add(a);
em.persist(a);
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@ManyToMany(mappedBy="authors")
private List<Book> books = new ArrayList<Book>();
...
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@ManyToMany
@JoinTable(name = "book_author",
joinColumns = { @JoinColumn(name = "fk_book") },
inverseJoinColumns = { @JoinColumn(name = "fk_author") })
private List<Author> authors = new ArrayList<Author>();
...
}
b = em.find(Book.class, 1L);
List<Author> authors = b.getAuthors();
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@ManyToMany(mappedBy="authors")
private List<Book> books = new ArrayList<Book>();
public void addBook(Book b) {
this.books.add(b);
b.getAuthors().add(this);
}
public void removeBook(Book b) {
this.books.remove(b);
b.getAuthors().remove(this);
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment