java_DAO类基本设计

package cn.itcast.oa.base;

import java.util.List;

public interface BaseDao<T> {

    void save(T entity);

    void delete(Long id);

    void update(T entity);

    T getById(Long id);

    List<T> getByIds(Long[] ids);

    List<T> findAll();
}
package cn.itcast.oa.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List; import javax.annotation.Resource; import org.hibernate.Session;
import org.hibernate.SessionFactory; @SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T> { @Resource
private SessionFactory sessionFactory;
protected Class<T> clazz; public BaseDaoImpl() {
// 通过反射得到T的真实类型 【0】数组是因为有可能 不只一个T
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
this.clazz = (Class) pt.getActualTypeArguments()[]; System.out.println("clazz = " + clazz.getName());
} public void save(T entity) {
getSession().save(entity);
} public void update(T entity) {
getSession().update(entity);
} public void delete(Long id) {
Object obj = getSession().get(clazz, id);
getSession().delete(obj);
} public T getById(Long id) {
return (T) getSession().get(clazz, id);
} public List<T> getByIds(Long[] ids) {
if (ids == null || ids.length == ) {
return Collections.EMPTY_LIST;
} return getSession().createQuery(//
"FROM " + clazz.getSimpleName() + " WHERE id IN(:ids)")//
.setParameterList("ids", ids)//
.list();
} public List<T> findAll() {
return getSession().createQuery(//
"FROM " + clazz.getSimpleName())//
.list();
} /**
* 获取当前可用的Session
*
* @return
*/
protected Session getSession() {
return sessionFactory.getCurrentSession();
} }
package cn.itcast.oa.dao;

import cn.itcast.oa.base.BaseDao;
import cn.itcast.oa.domain.Role; public interface RoleDao extends BaseDao<Role>{ }
package cn.itcast.oa.dao;

import cn.itcast.oa.base.BaseDao;
import cn.itcast.oa.domain.User; public interface UserDao extends BaseDao<User> { }
package cn.itcast.oa.dao.impl;

import org.springframework.stereotype.Repository;

import cn.itcast.oa.base.BaseDaoImpl;
import cn.itcast.oa.dao.RoleDao;
import cn.itcast.oa.domain.Role; @Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao { // public RoleDaoImpl(){
// clazz = Role.class;
// }
}
package cn.itcast.oa.dao.impl;

import org.springframework.stereotype.Repository;

import cn.itcast.oa.base.BaseDaoImpl;
import cn.itcast.oa.dao.UserDao;
import cn.itcast.oa.domain.User; @Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao { // public UserDaoImpl(){
// clazz = User.class;
// }
}

*设置抽象基类泛型,避免重复曾删改查代码

上一篇:Linux CentOS 防止SSH暴力破解


下一篇:mac下配置Node.js开发环境、express安装、创建项目