Package jpa.dao

Source Code of jpa.dao.GeneralDAO

package jpa.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;

@SuppressWarnings("deprecation")
public class GeneralDAO <T>
{
 
  private EntityManagerFactory entityManagerFactory;
  private Class<T> entityClass;
  private JpaTemplate jpaTemplate;
 
  public GeneralDAO(Class<T> clazz)
  {
    entityClass = clazz;
  }
 
  public void init()
  {
    jpaTemplate = new JpaTemplate(entityManagerFactory);
  }

  public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory)
  {
    this.entityManagerFactory = entityManagerFactory;
  }

  public EntityManagerFactory getEntityManagerFactory()
  {
    return entityManagerFactory;
  }

  @SuppressWarnings("unchecked")
  public List<T> findByNamedQuery(String queryName)
  {
    return jpaTemplate.findByNamedQuery(queryName);
  }
 
  public void deleteById(final byte id)
  {
    jpaTemplate.execute(new JpaCallback<T>()
      {
      @Override
      public T doInJpa(EntityManager em) throws PersistenceException
      {
        EntityTransaction tr =  em.getTransaction();
        tr.begin();
        Query que = em.createQuery(new StringBuilder().append("delete from ").append("FirstEntity").
            append(" where id = :id").toString());
        que.setParameter("id", Short.valueOf(id));
        que.executeUpdate();
        tr.commit();
        return null;
      }
    });
  }
 
  public void save(T entity)
  {
    EntityManager em =  jpaTemplate.getEntityManagerFactory().createEntityManager();
    EntityTransaction tr =  em.getTransaction();
    tr.begin();
    em.persist(entity);
    tr.commit();
  }
 
}
TOP

Related Classes of jpa.dao.GeneralDAO

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.