每个模型都需要有 dao、daoImpl、service、serviceImpl。
- 用户道
- UserDaoImpl
- 用户服务
- 用户服务简介
您可以使用泛型类 EntityDaoImpl anf inteface EntityDao,如下所示:
实体道:
public interface EntityDao<E> {
void persist(E e) throws Exception;
void remove(Object id) throws Exception;
E findById(Object id) throws Exception;
}
EntityDaoImpl:
public class EntityDaoImpl<E> implements EntityDao<E> {
@PersistenceContext(unitName="UnitPersistenceName")
protected EntityManager entityManager;
protected E instance;
private Class<E> entityClass;
@Transactional
public void persist(E e) throws HibernateException{
getEntityManager().persist(e);
}
@Transactional
public void remove(Object id) throws Exception{
getEntityManager().remove((E)getEntityManager().find(getEntityClass(), id));
}
public E findById(Object id) throws Exception {
return (E)getEntityManager().find(getEntityClass(), id);
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) throws Exception{
this.entityManager = entityManager;
}
public Class<E> getEntityClass() throws Exception{
if (entityClass == null) {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType)
{
ParameterizedType paramType = (ParameterizedType) type;
if (paramType.getActualTypeArguments().length == 2) {
if (paramType.getActualTypeArguments()[1] instanceof TypeVariable) {
throw new IllegalArgumentException(
"Can't find class using reflection");
}
else {
entityClass = (Class<E>) paramType.getActualTypeArguments()[1];
}
} else {
entityClass = (Class<E>) paramType.getActualTypeArguments()[0];
}
} else {
throw new Exception("Can't find class using reflection");
}
}
return entityClass;
}
}
你可以像这样使用:
public interface UserDao extends EntityDao<User> {
}
和
public class UserDaoImpl extends EntityDaoImpl<User> implements UserDao{
}