Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active December 18, 2016 18:31
Show Gist options
  • Save thjanssen/ab1131217c1c37353803183504e1d228 to your computer and use it in GitHub Desktop.
Save thjanssen/ab1131217c1c37353803183504e1d228 to your computer and use it in GitHub Desktop.
@Entity
public class Author {
@ManyToMany(mappedBy=”authors”, cascade = CascadeType.PERSIST)
private List<Book> books = new ArrayList<Book>();
}
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Author a = new Author();
a.setFirstName(“John”);
a.setLastName(“Doe”);
Book b1 = new Book();
b1.setTitle(“John’s first book”);
a.getBooks().add(b1);
Book b2 = new Book();
b2.setTitle(“John’s second book”);
a.getBooks().add(b2);
em.persist(a);
em.getTransaction().commit();
em.close();
15:44:28,140 DEBUG [org.hibernate.SQL] – insert into Author (firstName, lastName, version, id) values (?, ?, ?, ?)
15:44:28,147 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)
15:44:28,150 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment