package com.sm.framework.base;
import java.lang.reflect.ParameterizedType;
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.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.impl.SessionImpl;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import com.sm.framework.tag.paginate.Page;
import com.sm.framework.util.queryModel.QueryModel;
/**
* ��Ŀ��schoolMedia��Ŀ
*
* ������service�㸸�ֻ࣬�ṩ�ϼ�CRUD����
*
* ����ʱ�䣺2012-11-4 ����11:06:46 �����ˣ���С�� �汾��version 0.10
*
* ��ʱ�䣺2012-11-4 ����11:06:46 ���ˣ���С�� ���汾��version 0.10
*/
public abstract class BaseModel<T> {
/** ��������� */
private EntityManagerFactory entityManagerFactory;
/** Model��Ĭ��Class���� */
private Class<T> entityClass;
/** Model��Ĭ��Class����������������·�� */
private String entityClassName;
@SuppressWarnings("unchecked")
public BaseModel()
{
if (getClass().getGenericSuperclass() instanceof ParameterizedType)
{
entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
entityClassName = entityClass.getSimpleName();
}
}
// ********************************method********************************//
/**
* ���루��������ʵ��
* @param t
*/
public void save(Object obj)
{
getJpaTemplate().persist(obj);
}
/**
* ��������,ÿ100���ύһ��
* @Time 2011-12-20 ����04:24:10 create
* @param objList
* @return ����ʵ������
* @author �
*/
public int batchSave(List<T> objList)
{
return this.batchSave(objList, 100);
}
/**
* ��������,���ƶ��ύ�δ�С
* @Time 2011-12-20 ����04:24:32 create
* @param objList
* @param batchSize
* @return ����ʵ������
* @author �
*/
public int batchSave(List<T> objList, int batchSize)
{
//Ĭ��100���ύһ��
int bsize = 100;
if (batchSize > 0)
{
bsize = batchSize;
}
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Session session = (Session) em.getDelegate();
session.setFlushMode(FlushMode.MANUAL);
int i = 0;
for (T obj : objList)
{
session.save(obj);
i++;
if (i % bsize == 0)
{
session.flush();
session.clear();
}
}
et.commit();
return objList.size();
}
/**
* �����༭ʵ��,Ĭ��100���ύһ��
* @Time 2011-12-20 ����04:26:46 create
* @param objList
* @return
* @author �
*/
public int batchUpdate(List<T> objList)
{
return this.batchUpdate(objList, 100);
}
/**
* �����༭ʵ��,Ĭ��100���ύһ��,���Զ���δ�С
* @Time 2011-12-20 ����04:27:11 create
* @param objList
* @param batchSize
* @return
* @author �
*/
public int batchUpdate(List<T> objList, int batchSize)
{
//Ĭ��100���ύһ��
int bsize = 100;
if (batchSize > 0)
{
bsize = batchSize;
}
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Session session = (Session) em.getDelegate();
session.setFlushMode(FlushMode.MANUAL);
int i = 0;
for (T obj : objList)
{
session.update(obj);
i++;
if (i % bsize == 0)
{
session.flush();
session.clear();
}
}
et.commit();
return objList.size();
}
/**
* �����������£�Ĭ��100���ύһ��
* @Time 2011-12-20 ����04:28:47 create
* @param objList
* @return
* @author �
*/
public int batchSaveOrUpdate(List<T> objList)
{
return this.batchSaveOrUpdate(objList, 100);
}
/**
* �����������£�Ĭ��100���ύһ��,���ֹ��趨
* @Time 2011-12-20 ����04:29:07 create
* @param objList
* @param batchSize
* @return
* @author �
*/
public int batchSaveOrUpdate(List<T> objList, int batchSize)
{
//Ĭ��100���ύһ��
int bsize = 100;
if (batchSize > 0)
{
bsize = batchSize;
}
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Session session = (Session) em.getDelegate();
session.setFlushMode(FlushMode.MANUAL);
int i = 0;
for (T obj : objList)
{
session.saveOrUpdate(obj);
i++;
if (i % bsize == 0)
{
session.flush();
session.clear();
}
}
et.commit();
return objList.size();
}
/**
* ���£����ģ�ʵ��
* @param obj
*/
@SuppressWarnings("unchecked")
public <E extends BaseVO> E update(E obj)
{
getJpaTemplate().merge(obj);
return (E) getJpaTemplate().find(obj.getClass(), obj.getId());
}
/**
* ��������ʵ��
* @param obj
*/
@SuppressWarnings("unchecked")
public <E extends BaseVO> E saveOrUpdate(E obj)
{
if (null != obj.getId())
{
getJpaTemplate().merge(obj);
return (E) getJpaTemplate().find(obj.getClass(), obj.getId());
}
else
{
getJpaTemplate().persist(obj);
return obj;
}
}
/**
* ɾ��һ��ʵ��
* @param obj
*/
public void delete(T t)
{
getJpaTemplate().remove(t);
}
/**
* ɾ��һ����¼
* @param id
* @return int Ӱ������
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int delete(final Integer id)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = em.createQuery("DELETE FROM " + entityClassName + " WHERE id =" + id);
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ɾ��һ����¼
* @param id
* @return int Ӱ������
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int delete(final Long id)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = em.createQuery("DELETE FROM " + entityClassName + " WHERE id =" + id);
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ɾ��������¼
* @param ids
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int delete(final String ids)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = em.createQuery("DELETE FROM " + entityClassName + " WHERE id in(" + ids + ")");
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ��������ɾ��ʵ��
* @param model
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int deleteByModel(final QueryModel model)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = null;
if (null != model)
{
query = em.createQuery("DELETE FROM " + entityClassName + " WHERE 1=1 " + model);
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery("DELETE FROM " + entityClassName + " WHERE 1=1 ");
}
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ��������ɾ��ָ��ʵ��
* @param model
* @return int
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int deleteByModel(final Class<T> cls, final QueryModel model)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = null;
if (null != model)
{
query = em.createQuery("DELETE FROM " + cls.getSimpleName() + " WHERE 1=1 " + model);
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery("DELETE FROM " + cls.getSimpleName() + " WHERE 1=1 ");
}
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ����ID��ѯĬ��ʵ��
* @param id
* @return
*/
public T findById(Integer id)
{
T entity = (T) getJpaTemplate().find(entityClass, id);
return entity;
}
/**
* ����ID��ѯĬ��ʵ��
* @param id
* @return
*/
public T findById(Long id)
{
T entity = (T) getJpaTemplate().find(entityClass, id);
return entity;
}
/**
* �������Բ�ѯ����ʵ�壬����ģ��ƥ�䣬���ص���ʵ��
* @param propertyName
* @param value
* @return
*/
public T findByProperty(String propertyName, Object value)
{
List<T> list = queryByProperty(propertyName, value);
if (list.isEmpty())
{
return null;
}
else
{
return list.get(0);
}
}
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯĬ��ʵ�壬����ҳ
* @param model
* @return
*/
public T findByModel(final QueryModel model)
{
List<T> list = queryByModel(model);
if (list.isEmpty())
{
return null;
}
else
{
return list.get(0);
}
}
/**
* ����һ�����Բ�ѯĬ��ʵ�壬����ģ��ƥ�䣬����ʵ���б�
* @param propertyName
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public List<T> queryByProperty(String propertyName, Object value)
{
String queryString = "select model from " + entityClassName + " as model where model." + propertyName + "= ?";
return getJpaTemplate().find(queryString, value);
}
/**
* ͨ����ѡ��ids���еĶ����б�
* @param propertyName
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public List<T> queryInIds(String ids)
{
if (null == ids || "".equals(ids))
{
return null;
}
String queryString = "select model from " + entityClassName + " as model where model.id in(" + ids + ")";
return getJpaTemplate().find(queryString);
}
/**
* ��ѯ����ѡ��ID���еĶ����б�
* @param ids
* @return
* @author maoliang
*/
@SuppressWarnings("unchecked")
public List<T> queryWithoutIds(String ids)
{
String queryString = "select model from " + entityClassName + " as model where model.id not in(" + ids + ")";
return getJpaTemplate().find(queryString);
}
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯĬ��ʵ�壬����ҳ
* @param model
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> queryByModel(final QueryModel model)
{
return (List) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
String queryString = "select model from " + entityClassName + " as model where 1=1 ";
Query query = null;
if (null != model)
{
if (null != model.getColums())
{
queryString = "select " + model.getColums() + " from " + entityClassName + " as model where 1=1 ";
}
query = em.createQuery(queryString + model);
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery(queryString);
}
return query.getResultList();
}
});
}
// **********************************������ʵ��IJ�ѯ��ɾ��*************************************//
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯĬ��ʵ�壬��ҳ
* @param model
* @param page
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> queryPageByModel(final QueryModel model, final Page page)
{
return (List) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
String queryString = "select model from " + entityClassName + " as model where 1=1 ";
String countString = "select count(*) from " + entityClassName + " where 1=1 ";
Query query = null;
Query queryCount = null;
if (null != model)
{
if (null != model.getColums())
{
queryString = "select " + model.getColums() + " from " + entityClassName + " as model where 1=1 ";
}
query = em.createQuery(queryString + model);
queryCount = em.createQuery(countString + model.getQueryCondition());
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
queryCount.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery(queryString);
queryCount = em.createQuery(countString);
}
page.setCount((Long) queryCount.getSingleResult());// ��������д
query.setFirstResult((page.getTargetPage() - 1) * page.getPageSize());
query.setMaxResults(page.getPageSize());
return query.getResultList();
}
});
}
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯָ��ʵ�壬����ҳ
* @param model
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <E> List<E> queryByModel(final Class<E> cls, final QueryModel model)
{
return (List<E>) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
String queryString = "select model from " + cls.getSimpleName() + " as model where 1=1 ";
Query query = null;
if (null != model)
{
if (null != model.getColums())
{
queryString = "select " + model.getColums() + " from " + cls.getSimpleName() + " as model where 1=1 ";
}
query = em.createQuery(queryString + model);
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery(queryString);
}
return query.getResultList();
}
});
}
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯָ��ʵ�壬��ҳ
* @param model
* @param page
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <E> List<E> queryPageByModel(final Class<E> cls, final QueryModel model, final Page page)
{
return (List<E>) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
String queryString = "select model from " + cls.getSimpleName() + " as model where 1=1 ";
String countString = "select count(*) from " + cls.getSimpleName() + " where 1=1 ";
Query query = null;
Query queryCount = null;
if (null != model)
{
if (null != model.getColums())
{
queryString = "select " + model.getColums() + " from " + cls.getSimpleName() + " as model where 1=1 ";
}
query = em.createQuery(queryString + model);
queryCount = em.createQuery(countString + model.getQueryCondition());
if (!model.getPreConditionMap().isEmpty())
{
for (String key : model.getPreConditionMap().keySet())
{
query.setParameter(key, model.getPreConditionMap().get(key));
queryCount.setParameter(key, model.getPreConditionMap().get(key));
}
}
}
else
{
query = em.createQuery(queryString);
queryCount = em.createQuery(countString);
}
page.setCount((Long) queryCount.getSingleResult());// ��������д
query.setFirstResult((page.getTargetPage() - 1) * page.getPageSize());
query.setMaxResults(page.getPageSize());
return query.getResultList();
}
});
}
/**
* ��ȡͶӰ
* @param cls
* @param columns
* @return
*/
@SuppressWarnings({ "rawtypes", "unused" })
private String getProjection(Class cls, String columns)
{
String projection = null;
if (null == columns)
{
projection = cls.getSimpleName().toLowerCase();
}
else
{
projection = "new " + cls.getSimpleName() + "(" + columns + ")";
}
return projection;
}
/**
* �ͷŲ�ѯ������
* @param em
*/
protected void releaseManager(EntityManager em)
{
if (null != em)
{
em.clear();
em.close();
}
}
/**
* ����ID��ѯָ����ʵ��
* @param <E>
* @param cls
* @param id
* @return
*/
public <E> E findById(Class<E> cls, Integer id)
{
return (E) getJpaTemplate().find(cls, id);
}
/**
* ����һ�����Բ�ѯָ��ʵ�壬����ģ��ƥ�䣬���ص���ʵ��
* @param <E>
* @param cls
* @param propertyName
* @param value
* @return
*/
public <E> E findByProperty(Class<E> cls, String propertyName, Object value)
{
List<E> list = queryByProperty(cls, propertyName, value);
if (list.isEmpty())
{
return null;
}
else
{
return list.get(0);
}
}
/**
* ���ݲ�ѯ�����ַ���ʵ���ѯָ��ʵ�壬���ص�һ��ʵ��
* @param <E>
* @param cls
* @param model
* @return
*/
public <E> E findByModel(final Class<E> cls, final QueryModel model)
{
List<E> list = queryByModel(cls, model);
if (list.isEmpty())
{
return null;
}
else
{
return list.get(0);
}
}
/**
* ����һ�����Բ�ѯָ��ʵ�壬����ģ��ƥ�䣬����ʵ���б�
* @param className
* @param propertyName
* @param value
* @return List<E>
*/
@SuppressWarnings("unchecked")
public <E> List<E> queryByProperty(Class<E> cls, String propertyName, Object value)
{
String queryString = "select model from " + cls.getSimpleName() + " as model where model." + propertyName + "= ?";
return (List<E>) getJpaTemplate().find(queryString, value);
}
/**
* ɾ��һ����¼�����Զ����
* @param cls
* @param id
* @return int Ӱ������
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int delete(final Class cls, final Integer id)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = em.createQuery("DELETE FROM " + cls.getSimpleName() + " WHERE id =" + id);
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ɾ��������¼�����Զ����
* @param cls
* @param ids
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public int delete(final Class cls, final String ids)
{
int rowcount = 0;
rowcount = (Integer) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
Query query = em.createQuery("DELETE FROM " + cls.getSimpleName() + " WHERE id in(" + ids + ")");
return query.executeUpdate();
}
});
return rowcount;
}
/**
* ����ע�ⷽʽ��ȡEntityManagerʵ�壬�ݼ��ڴˣ���������
* @PersistenceContext(unitName="xxxx") EntityManager em;
*/
/**
* ��ȡ���ݿⷽ��
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Dialect getDialect()
{
return (Dialect) getJpaTemplate().execute(new JpaCallback()
{
public Object doInJpa(EntityManager em) throws PersistenceException
{
SessionImpl session = (SessionImpl) em.getDelegate();
return session.getFactory().getDialect();
}
});
}
/**
* ��ȡ���ݿⷽ����
* @return
* @author maoliang
*/
public String getDialectName()
{
return getDialect().getClass().getName();
}
// ********************************setter getter*************************//
public void setEntityManagerFactory(EntityManagerFactory emf)
{
this.entityManagerFactory = emf;
}
private synchronized JpaTemplate getJpaTemplate()
{
JpaTemplate jpaTemplate = new JpaTemplate(entityManagerFactory);
return jpaTemplate;
}
}