package cn.lvpeng.base;
import java.util.LinkedHashMap;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import cn.lvpeng.service.QueryResult;
@Component
public class BaseDaoImpl<T> implements BaseDao<T> {
//@Resource可以理解为资源->数据源->也就是数据连接,基本上就是告诉程序数据库在哪里
//@PersistenceContext 注入的是实体管理器,执行持久化操作的,需要配置文件persistence.xml。
@PersistenceContext
protected EntityManager em;
@Override
public void delete(T entity) {
em.remove(em.merge(entity));
}
@Override
public void save(T entity) {
em.persist(entity);
}
@Override
public void update(T entity) {
em.merge(entity);
}
@Override
public T find(Class<T> clazz, Integer id) {
return em.find(clazz, id);
}
/**
*
* 总记录
*
* */
@Override
public QueryResult<T> getScrollData(Class<T> clazz){
return getScrollData(clazz,-1,-1,null,null,null);
}
/**
*
* 记录分页
*
* */
@Override
public QueryResult<T> getScrollData(Class<T> clazz,int startIndex,int maxSize){
return getScrollData(clazz,startIndex,maxSize,null,null,null);
}
/**
*
* 记录分页,排序
*
* */
@Override
public QueryResult<T> getScrollData(Class<T> clazz,int startIndex,int maxSize,LinkedHashMap<String,String> orderby){
return getScrollData(clazz,startIndex,maxSize,null,null,orderby);
}
/**
*
* 记录分页,条件查询,排序
*
* */
@SuppressWarnings("unchecked")
@Override
public QueryResult<T> getScrollData(Class<T> clazz, int startIndex,
int maxSize,String whereJPQL,Object[] params,LinkedHashMap<String, String> orderby) {
String orderbyString=getOrderby(orderby);//设置排序方式
String where=(whereJPQL!=null&&!"".equals(whereJPQL.trim()))?"where "+whereJPQL:"";
String JPQL="from "+clazz.getName()+" o "+where+orderbyString;
List<T> list=null;
Query query1=em.createQuery(JPQL);
setParams(query1,params);//设置参数
if(startIndex!=-1&&maxSize!=-1){
query1.setFirstResult(startIndex);
query1.setMaxResults(maxSize);
}
list=query1.getResultList();
Query query2=em.createQuery("select count(*) from "+clazz.getName()+" o "+where);
setParams(query2, params);
long totalRecord=(Long)query2.getSingleResult();
QueryResult<T> result=new QueryResult<T>();
result.setResult(list);
result.setTotalRecord(totalRecord);
return result;
}
/*
*
* 设置排序条件
*
* */
private String getOrderby(LinkedHashMap<String, String> orderby) {
StringBuilder str=new StringBuilder();
String orderbyString="";
if(orderby!=null&&orderby.size()>0){
str.append(" order by o.");
for(String key:orderby.keySet()){
str.append(key).append(" ").append(orderby.get(key)).append(",o.");
}
orderbyString=str.substring(0, str.length()-3);
}
return orderbyString;
}
/*
*
* 设置查询条件参数。
*
* */
private void setParams(Query query, Object[] params) {
if(params!=null&¶ms.length!=0){
for(int i=0;i<params.length;i++){
query.setParameter(i+1, params[i]);
}
}
}
}