通用DAO层接口:ICommonDao:
package com.lrq.dao.base;
import java.io.Serializable;
import java.util.Collection;
public interface ICommonDao {
public void persist(T t);
public void delete(Serializable id);
public void update(T t);
public T get(Class clazz,Serializable id);
public Collection listAll();
}
通用Dao实现CommonDaoImpl:
package com.lrq.dao.base.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.lrq.dao.base.ICommonDao;
public abstract class CommonDaoImpl implements ICommonDao {
private Class clazz;
@Autowired
public HibernateTemplate hibernateTemplate;
public CommonDaoImpl() {
ParameterizedType type = (ParameterizedType) this.getClass()
.getGenericSuperclass();
clazz = (Class) type.getActualTypeArguments()[0];
}
public void persist(T t) {
if (t != null)
hibernateTemplate.persist(t);
}
@SuppressWarnings("unchecked")
public void delete(Serializable id) {
if (id != null) {
Object entity = hibernateTemplate.get(clazz, id);
if (entity != null)
hibernateTemplate.delete(entity);
}
}
public void update(T t) {
if (t != null) {
hibernateTemplate.update(t);
}
}
@SuppressWarnings("unchecked")
public T get(Class clazz, Serializable id) {
return (T) (id == null ? null : hibernateTemplate.get(clazz, id));
}
@SuppressWarnings("unchecked")
public Collection listAll() {
return hibernateTemplate.find("from " + clazz.getSimpleName());
}
}
具体的某个实体DAO:
package com.lrq.dao;
import java.util.Collection;
import com.lrq.dao.base.ICommonDao;
import com.lrq.domain.Privilege;
public interface IPrivilegeDao extends ICommonDao {
public Privilege getPrivilegeByName(String nodeName);
public Collection getPrivilegesByIds(String ids);
}
对应的Dao实现:
package com.lrq.dao.impl;
import java.util.Collection;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.lrq.dao.IPrivilegeDao;
import com.lrq.dao.base.impl.CommonDaoImpl;
import com.lrq.domain.Privilege;
import com.lrq.util.StringUtils;
import freemarker.template.utility.StringUtil;
@Repository
public class PrivilegeDaoImpl extends CommonDaoImpl implements
IPrivilegeDao {
@SuppressWarnings("unchecked")
public Privilege getPrivilegeByName(String nodeName) {
// 如果 入的参数都为null,我认为没必要和数据库进行交互,直接返回null;
if (StringUtils.isEmpty(nodeName))
return null;
List list = hibernateTemplate.find(
"from Privilege where name=?", nodeName);
return list != null && list.size() > 0 ? list.get(0) : null;
}
@SuppressWarnings("unchecked")
public Collection getPrivilegesByIds(String ids) {
if (!StringUtils.isEmpty(ids)) {
StringBuffer sb = new StringBuffer();
sb.append("from Privilege where id in(");
sb.append(ids);
sb.append(" )");
System.out.println(sb.toString());
List list = this.hibernateTemplate.find(sb.toString());
return list;
}
return null;
}
}
注意:通用的Dao实现是一个抽象类,而且必须这么做;因为他不能有实例对象
转发至微博
转发至微博