在dao层上还可以包含一层,比如叫business,但是比dao更复杂点,一般一个dao类只对一个表操作,但是business可能会同时操作几个dao,这里不介绍。
dao也叫数据访问层,里面包含了对数据库的操作,所以就涉及到事务操作。 结合了JPA后,dao层就显得简单了,比如Userdao设计如下:
先定义一个接口dao,然后DaoSupport
1.dao
package com.jimmy.godutch.service.base;
import java.io.Serializable;
import java.util.LinkedHashMap;
import com.jimmy.godutch.bean.QueryResult;
public interface DAO
/**
* 获取记录总数
* @param entityClass 实体类
* @return
*/
public long getCount();
/**
* 清除一级缓存的数据
*/
public void clear();
/**
* 保存实体
* @param entity 实体id
*/
public void save(T entity);
/**
* 更新实体
* @param entity 实体id
*/
public void update(T entity);
/**
* 删除实体
* @param entityClass 实体类
* @param entityids 实体id数组
*/
public void delete(Serializable ... entityids);
/**
* 获取实体
* @param
* @param entityClass 实体类
* @param entityId 实体id
* @return
*/
public T find(Serializable entityId);
/**
* 获取分页数据
* @param
* @param entityClass 实体类
* @param firstindex 开始索引
* @param maxresult 需要获取的记录数
* @return
*/
public QueryResult
public QueryResult
public QueryResult
public QueryResult
public QueryResult
}
2 DaoSupport
package com.jimmy.godutch.service.base;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
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.jimmy.godutch.bean.QueryResult;
import com.jimmy.godutch.util.GenericsUtils;
public abstract class DaoSupport
protected Class
@PersistenceContext protected EntityManager em;
public void clear(){
em.clear();
}
public void delete(Serializable ... entityids) {
for(Object id : entityids){
em.remove(em.getReference(this.entityClass, id));
}
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public T find(Serializable entityId) {
if(entityId==null) throw new RuntimeException(this.entityClass.getName()+ ":传入的实体id不能为空");
return em.find(this.entityClass, entityId);
}
public void save(T entity) {
em.persist(entity);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public long getCount() {
return (Long)em.createQuery("select count("+ getCountField(this.entityClass) +") from "+ getEntityName(this.entityClass)+ " o").getSingleResult();
}
public void update(T entity) {
em.merge(entity);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public QueryResult
return getScrollData(firstindex,maxresult,null,null,orderby);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public QueryResult
return getScrollData(firstindex,maxresult,wherejpql,queryParams,null);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public QueryResult
return getScrollData(firstindex,maxresult,null,null,null);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public QueryResult
return getScrollData(-1, -1);
}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public QueryResult
, String wherejpql, Object[] queryParams,LinkedHashMap
QueryResult qr = new QueryResult
String entityname = getEntityName(this.entityClass);
Query query = em.createQuery("select o from "+ entityname+ " o "+(wherejpql==null || "".equals(wherejpql.trim())? "": "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(this.entityClass)+ ") from "+ entityname+ " o "+(wherejpql==null || "".equals(wherejpql.trim())? "": "where "+ wherejpql));
setQueryParams(query, queryParams);
qr.setTotalrecord((Long)query.getSingleResult());
return qr;
}
protected static void setQueryParams(Query query, Object[] queryParams){
if(queryParams!=null && queryParams.length>0){
for(int i=0; i
}
}
}
/**
* 组装order by语句
* @param orderby
* @return
*/
protected static String buildOrderby(LinkedHashMap
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
* @param clazz 实体类
* @return
*/
protected static
String entityname = clazz.getSimpleName();
Entity entity = clazz.getAnnotation(Entity.class);
if(entity.name()!=null && !"".equals(entity.name())){
entityname = entity.name();
}
return entityname;
}
/**
* 获取统计属性,该方法是为了解决hibernate解析联合主键select count(o) from Xxx o语句BUG而增加,hibernate对此jpql解析后的sql为select count(field1,field2,...),显示使用count()统计多个字段是错误的
* @param
* @param clazz
* @return
*/
protected static
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;
}
}
3.UserService 接口 ,为了实现在servlet注入 ,
public interface UserService extends DAO
public int findByUsernameAndPwd(String name,String pwd);
}
3.UserServiceBean 里面代码简单多了 ,实现 UserService 接口(虽然没什么用,但是不实现接口的话,在servlet层会报:
ory.NoSuchBeanDefinitionException: No matching bean of type [com.jimmy.godutch.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}
package com.jimmy.godutch.service;
@Service
public class UserServiceBean extends DaoSupport
public int findByUsernameAndPwd(String name,String pwd){
Query q=em.createQuery("select u from User u where u.name=?1 and u.pwd=?2");
q.setParameter(1, name);
q.setParameter(2, pwd);
return q.getResultList().size()>0?1:0;
}
public static void main(String[]ss)
{
BeanFactory ac = new FileSystemXmlApplicationContext("D:\\study\\hongwash\\sns4j_workspace\\GoDutchServer\\src\\beans.xml");
EntityManagerFactory entityManagerFactory=(EntityManagerFactory)ac.getBean("entityManagerFactory");
EntityManager em=entityManagerFactory.createEntityManager();
//em.setFlushMode(FlushMode.AUTO);
em.persist(new User("jimmy2","jimmy2"));
System.out.println("hello");
}
}