首页 > 代码库 > java_DAO类基本设计
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的真实类型 ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); this.clazz = (Class) pt.getActualTypeArguments()[0]; 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 == 0) { 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;@Repositorypublic 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;@Repositorypublic class UserDaoImpl extends BaseDaoImpl<User> implements UserDao { // public UserDaoImpl(){ // clazz = User.class; // }}
java_DAO类基本设计
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。