org.hellospring4.dao.AbstractDAO.java Source code

Java tutorial

Introduction

Here is the source code for org.hellospring4.dao.AbstractDAO.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.hellospring4.dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author giovanni
 * @param <T>
 */
public abstract class AbstractDAO<T extends Serializable> {
    private Class<T> entityClass;

    @PersistenceContext
    EntityManager entityManager;

    public EntityManager getEntityMgr() {
        return entityManager;
    }

    public void setClass(Class<T> classToSet) {
        this.entityClass = classToSet;
    }

    public T find(Object id) {
        return entityManager.find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return entityManager.createQuery(cq).getResultList();
    }

    @Transactional
    public void create(T entity) {
        entityManager.persist(entity);
    }

    @Transactional
    public T update(T entity) {
        return entityManager.merge(entity);
    }

    @Transactional
    public void delete(T entity) {
        entityManager.remove(entity);
    }

    public void deleteById(Object id) {
        T entity = find(id);
        delete(entity);
    }

}