John Manak John Manak - 6 months ago 134
Java Question

Single DAO & generic CRUD methods (JPA/Hibernate + Spring)

Following my previous question, DAO and Service layers (JPA/Hibernate + Spring), I decided to use just a single DAO for my data layer (at least at the beginning) in an application using JPA/Hibernate, Spring and Wicket. The use of generic CRUD methods was proposed, but I'm not very sure how to implement this using JPA. Could you please give me an example or share a link regarding this?


Here is an example interface:

public interface GenericDao<T, PK extends Serializable> {
    T create(T t);
    T read(PK id);
    T update(T t);
    void delete(T t);

And an implementation:

public class GenericDaoJpaImpl<T, PK extends Serializable> 
    implements GenericDao<T, PK> {

    protected Class<T> entityClass;

    protected EntityManager entityManager;

    public GenericDaoJpaImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
        this.entityClass = (Class<T>) genericSuperclass

    public T create(T t) {
        return t;

    public T read(PK id) {
        return this.entityManager.find(entityClass, id);

    public T update(T t) {
        return this.entityManager.merge(t);

    public void delete(T t) {
        t = this.entityManager.merge(t);