利用java 泛型实现BaseDao

package com.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class BaseDao<T> {

 @PersistenceContext
 private EntityManager em;

 public void persist(T t) {
  em.persist(t);
 }

 @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
 public T save(T t) {
  return em.merge(t);
 }
 
 public void delete(T t){
  em.remove(t);
 }
 
 @Transactional(readOnly=true,isolation=Isolation.READ_COMMITTED)
 public T find(Class<T> clazz,Serializable id){
  return em.getReference(clazz, id);
 }
 
 @SuppressWarnings("unchecked")
 public List<T> find(String jpql){
  return em.createQuery(jpql).getResultList();
 }
 
 @SuppressWarnings("unchecked")
 public List<T> find(String jpql,Object param){
  return em.createQuery(jpql).setParameter(1, param).getResultList();
 }
 
 @SuppressWarnings("unchecked")
 public List<T> find(String jpql,Object[] param){
  Query query=em.createQuery(jpql);
  for(int i=1;i<=param.length;i++){
   query.setParameter(i, param[i-1]);
  }
  return query.getResultList();
 }
 
 public int findTotalCount(String jpql){
  return ((Long)em.createQuery(jpql).getSingleResult()).intValue();
 }
}

你可能感兴趣的:(利用java 泛型实现BaseDao)