标签:style blog color io os java ar div sp
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; @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; // } }
标签:style blog color io os java ar div sp
原文地址:http://www.cnblogs.com/MarchThree/p/3969879.html