package com.chenyang.nse.bussiness.dao;

import com.chenyang.nse.bussiness.HibernateSessionFactory;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

@Transactional
public class BaseDao222<T, PK extends Serializable> {
   private Class<T> entityClass;
   @PersistenceContext
   protected EntityManager entityManager;

   protected BaseDao222() {
      Type genType = this.getClass().getGenericSuperclass();
      Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
      this.entityClass = (Class)params[0];
   }

   public Class<T> getEntityClass() {
      return this.entityClass;
   }

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

   public EntityManager getEntityManager() {
      return this.entityManager;
   }

   public void save(T entity) {
      this.entityManager.persist(entity);
      this.entityManager.flush();
   }

   public void update(PK id) {
      T entity = (T)this.findByID(id);
      this.entityManager.merge(entity);
      this.entityManager.flush();
   }

   public void delete(PK id) {
      T entity = (T)this.findByID(id);
      this.entityManager.remove(entity);
   }

   public List<T> queryAll() {
      Query query = this.entityManager.createQuery("");
      return query.getResultList();
   }

   public List<T> queryAll(Criteria criteria) {
      return criteria.list();
   }

   public List<T> queryAll(String orderBy, boolean isAsc) {
      return isAsc ? this.createCriteria().addOrder(Order.asc(orderBy)).list() : this.createCriteria().addOrder(Order.desc(orderBy)).list();
   }

   public Criteria createCriteria() {
      return this.getSession().createCriteria(this.entityClass);
   }

   public Session getSession() {
      return HibernateSessionFactory.getSession();
   }

   public T get(PK id) {
      T pojo = (T)this.entityManager.find(this.entityClass, id);
      return pojo;
   }

   public void remove(PK id) {
      T entity = (T)this.findByID(id);
      this.entityManager.remove(entity);
   }

   public void remove(T o) {
      this.entityManager.remove(o);
   }

   public void removeById(PK id) {
      T o = (T)this.get(id);
      this.remove(o);
   }

   public void remove(Collection<T> entities) {
      if (entities != null) {
         for(T entity : entities) {
            this.remove(entity);
         }

      }
   }

   public T findByID(PK id) {
      T pojo = (T)this.entityManager.find(this.entityClass, id);
      return pojo;
   }

   public List<T> findAll(String qlString) {
      Query query = this.entityManager.createQuery(qlString);
      return query.getResultList();
   }
}
