Explaining The Repository Pattern
Explaining The Repository Pattern
www.thoughts-on-java.org
Implementing the Repository pattern
especially complex. I will show you more of that in the following
articles of this series.
But for now, let's implement the repository pattern without any
frameworks. That makes the pattern easier to understand and
highlights the benefits of frameworks that generate repetitive parts
of the implementation.
www.thoughts-on-java.org
Implementing the Repository pattern
Implementing the repository with JPA and Hibernate
In the next step, you can implement the BookRepository interface.
@Override
public Book getBookById(Long id) {
return em.find(Book.class, id);
}
@Override
public Book getBookByTitle(String title) {
TypedQuery<Book> q = em.createQuery("SELECT b FROM Book b
WHERE b.title = :title", Book.class);
q.setParameter("title", title);
return q.getSingleResult();
}
@Override
public Book saveBook(Book b) {
if (b.getId() == null) {
em.persist(b);
} else {
b = em.merge(b);
}
return b;
}
@Override
www.thoughts-on-java.org
public void deleteBook(Book b) {
Implementing the Repository pattern
@Override
public void deleteBook(Book b) {
if (em.contains(b)) {
em.remove(b);
} else {
em.merge(b);
}
}
}
www.thoughts-on-java.org