打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring+JPA 通用DAO及实现
userphoto

2011.05.22

关注
Spring+JPA 通用DAO及实现 收藏
接口:
view plaincopy to clipboardprint?
import java.util.LinkedHashMap;
import com.itcast.bean.QueryResult;
public interface DAO {
/**
* 获取记录总数
* @param entityClass 实体类
* @return
*/
public <T> long getCount(Class<T> entityClass);
/**
* 清除一级缓存的数据
*/
public void clear();
/**
* 保存实体
* @param entity 实体id
*/
public void save(Object entity);
/**
* 更新实体
* @param entity 实体id
*/
public void update(Object entity);
/**
* 删除实体
* @param entityClass 实体类
* @param entityid 实体id
*/
public <T> void delete(Class<T> entityClass, Object entityid);
/**
* 删除实体
* @param entityClass 实体类
* @param entityids 实体id数组
*/
public <T> void delete(Class<T> entityClass, Object[] entityids);
/**
* 获取实体
* @param <T>
* @param entityClass 实体类
* @param entityId 实体id
* @return
*/
public <T> T find(Class<T> entityClass, Object entityId);
/**
* 获取分页数据
* @param <T>
* @param entityClass 实体类
* @param firstindex 开始索引
* @param maxresult 需要获取的记录数
* @return
*/
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult
, String wherejpql, Object[] queryParams,LinkedHashMap<String, String> orderby);
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult
, String wherejpql, Object[] queryParams);
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult
, LinkedHashMap<String, String> orderby);
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult);
public <T> QueryResult<T> getScrollData(Class<T> entityClass);
}
 
实现类:
view plaincopy to clipboardprint?
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.itcast.bean.QueryResult;
@Transactional
public abstract class DaoSupport implements DAO{
@PersistenceContext protected EntityManager em;
public void clear(){
em.clear();
}
public <T> void delete(Class<T> entityClass,Object entityid) {
delete(entityClass, new Object[]{entityid});
}
public <T> void delete(Class<T> entityClass,Object[] entityids) {
for(Object id : entityids){
em.remove(em.getReference(entityClass, id));
}
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> T find(Class<T> entityClass, Object entityId) {
return em.find(entityClass, entityId);
}
public void save(Object entity) {
em.persist(entity);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> long getCount(Class<T> entityClass) {
return (Long)em.createQuery("select count("+ getCountField(entityClass) +") from "+ getEntityName(entityClass)+ " o").getSingleResult();
}
public void update(Object entity) {
em.merge(entity);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass,
int firstindex, int maxresult, LinkedHashMap<String, String> orderby) {
return getScrollData(entityClass,firstindex,maxresult,null,null,orderby);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass,
int firstindex, int maxresult, String wherejpql, Object[] queryParams) {
return getScrollData(entityClass,firstindex,maxresult,wherejpql,queryParams,null);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult) {
return getScrollData(entityClass,firstindex,maxresult,null,null,null);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass) {
return getScrollData(entityClass, -1, -1);
}
@SuppressWarnings("unchecked")
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult
, String wherejpql, Object[] queryParams,LinkedHashMap<String, String> orderby) {
QueryResult qr = new QueryResult<T>();
String entityname = getEntityName(entityClass);
Query query = em.createQuery("select o from "+ entityname+ " o "+(wherejpql==null? "": "where "+ wherejpql)+ buildOrderby(orderby));
setQueryParams(query, queryParams);
if(firstindex!=-1 && maxresult!=-1) query.setFirstResult(firstindex).setMaxResults(maxresult);
qr.setResultlist(query.getResultList());
query = em.createQuery("select count("+ getCountField(entityClass)+ ") from "+ entityname+ " o "+(wherejpql==null? "": "where "+ wherejpql));
setQueryParams(query, queryParams);
qr.setTotalrecord((Long)query.getSingleResult());
return qr;
}
protected void setQueryParams(Query query, Object[] queryParams){
if(queryParams!=null && queryParams.length>0){
for(int i=0; i<queryParams.length; i++){
query.setParameter(i+1, queryParams[i]);
}
}
}
/**
* 组装order by语句
* @param orderby
* @return
*/
protected String buildOrderby(LinkedHashMap<String, String> orderby){
StringBuffer orderbyql = new StringBuffer("");
if(orderby!=null && orderby.size()>0){
orderbyql.append(" order by ");
for(String key : orderby.keySet()){
orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");
}
orderbyql.deleteCharAt(orderbyql.length()-1);
}
return orderbyql.toString();
}
/**
* 获取实体的名称
* @param <T>
* @param entityClass 实体类
* @return
*/
protected <T> String getEntityName(Class<T> entityClass){
String entityname = entityClass.getSimpleName();
Entity entity = entityClass.getAnnotation(Entity.class);
if(entity.name()!=null && !"".equals(entity.name())){
entityname = entity.name();
}
return entityname;
}
protected <T> String getCountField(Class<T> clazz){
String out = "o";
try {
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
for(PropertyDescriptor propertydesc : propertyDescriptors){
Method method = propertydesc.getReadMethod();
if(method!=null && method.isAnnotationPresent(EmbeddedId.class)){
PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType()).getPropertyDescriptors();
out = "o."+ propertydesc.getName()+ "." + (!ps[1].getName().equals("class")? ps[1].getName(): ps[0].getName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
}
 
beans.xml:
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="com.itcast"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="itcast"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Activates @Transactional for DefaultImageDatabase -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
s2sh 底层封装(增,删,改,查,分页)
hibernate--basedao,借鉴别人的完善自己的
hibernate DAO 泛型 另
mongodb 3.2 实战(三)整合Spring Data MongoDB
hibernate标准查询
spring4.x + hibernate4.x 配置详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服