在我的spring项目中,我的Dao类具有以下模板:
public class Dao<E> { private final E entity; @Autowired SessionFactory sessionFactory; protected Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } public Dao(E entity) { this.entity = entity; } public Dao(Class<?> classe) { this.entity = (E) classe; } public E getEntity() { return this.entity; } @Transactional public boolean persist(E transientInstance) { sessionFactory.getCurrentSession().persist(transientInstance); return true; } @Transactional public boolean remove(E transientInstance) { sessionFactory.getCurrentSession().delete(transientInstance); return true; } @Transactional public boolean merge(E detachedInstance) { sessionFactory.getCurrentSession().merge(detachedInstance); return true; } @Transactional public E findById(int id) { E instance = (E) sessionFactory.getCurrentSession().get(entity.getClass(), id); return instance; } @Transactional public E findByField(String field, String value) { String expressao = entity.toString(); String nome_classe = new String(); StringTokenizer st = new StringTokenizer(expressao); while (st.hasMoreTokens()) { nome_classe = st.nextToken(); } String query = "from "+nome_classe+" where "+field+" = :data"; Query q = sessionFactory.getCurrentSession().createQuery(query); q.setParameter("data", value); E instance = (E) q.uniqueResult(); return instance; } @Transactional public List<E> findAll() { List<E> instance = (List<E>) sessionFactory.getCurrentSession().createSQLQuery("select * from usuario").list(); return instance; } }
我的每个Dao类都具有以下结构:
@Repository public class UsuarioHome extends Dao<Usuario> { public UsuarioHome() { super(Usuario.class); } }
这意味着当我调用方法findById,findByField,findAll时,我应该从Usuario,Usuario和List类型接收对象。
这两个拳头类的返回正确值,但最后一个不返回。当我运行此方法时(从我的服务类中):
@Transactional public List<Usuario> listagem_usuarios() { List<Usuario> lista = usuario.findAll(); System.out.println("listagem_usuario find "+lista.size()+" users"); System.out.println(lista.getClass().getName()); for(int i=0; i<lista.size(); i++) { System.out.println("i = "+i+" {"); if(lista.get(i) instanceof Usuario) System.out.println("usuario"); else if(lista.get(i) instanceof Object) System.out.println("object"); else System.out.println("outro"); System.out.println("}"); } return lista; }
我应该看到“ usuario”时收到“对象”作为响应。有人可以告诉我我在做什么错吗?
问题出在您的通用DAOfindAll方法中。您正在使用查询字符串select * from usuario
DAO
select * from usuario
@Transactional public List<E> findAll() { List<E> instance = (List<E>) sessionFactory.getCurrentSession().createSQLQuery("select * from usuario").list(); return instance; }
怎么这样尝试?
@Transactional public List<E> findAll() { return (List<E>) sessionFactory.getCurrentSession().createCriteria(entity) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); }
这也是关于模板DAO类的建议;
我更喜欢这个变量声明
private Class<E> entity;
并在带有class参数的构造函数中
class
public Dao(Class<E> clazz) { this.entity = clazz;
}