Java的泛型封装方式
package base;
import java.util.List;
public interface DaoSupport<T> {
/**
* 保存实体
*
* @param entity
*/
void save(T entity);
/**
* 删除实体
*
* @param id
*/
void delete(Long id);
/**
* 更新实体
*
* @param entity
*/
void update(T entity);
/**
* 按id查询
*
* @param id
* @return
*/
T getById(Long id);
/**
* 按id查询
*
* @param ids
* @return
*/
List<T> getByIds(Long[] ids);
/**
* 查询所有
*
* @return
*/
List<T> findAll();
}
package base;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@SuppressWarnings("unchecked")
public abstract class DaoSupportImpl<T> implements DaoSupport<T> {
@Resource
private SessionFactory sessionFactory;
private Class<T> clazz;
public DaoSupportImpl() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
this.clazz = (Class<T>) pt.getActualTypeArguments()[0];
System.out.println("clazz ---> " + clazz);
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
public void save(T entity) {
getSession().save(entity);
}
public void update(T entity) {
getSession().update(entity);
}
public void delete(Long id) {
Object obj = getById(id);
if (obj != null) {
getSession().delete(obj);
}
}
public T getById(Long id) {
if (id == null) {
return null;
} else {
return (T) getSession().get(clazz, id);
}
}
public List<T> getByIds(Long[] ids) {
if (ids == null || ids.length == 0) {
return Collections.EMPTY_LIST;
} else {
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();
}
}
package service;
import pojo.User;
import base.DaoSupport;
public interface UserService extends DaoSupport<User> {
}
package service.impl;
import java.util.List;
import base.DaoSupportImpl;
import pojo.User;
import service.UserService;
public class UserServiceImpl extends DaoSupportImpl<User> implements UserService {
}