In my spring project, I have this template for my Dao classes:
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;
}
}
Each one of my Dao classes have this structure:
@Repository
public class UsuarioHome extends Dao<Usuario> {
public UsuarioHome() {
super(Usuario.class);
}
}
Which means that when I call the methods findById, findByField, findAll, I should receive a object from types Usuario, Usuario and List.
The two fist classesa re returning the right value, but the Last one don't. When I run this method (from my service class):
@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;
}
I am receiving "object" as response, when I should see "usuario". Anyone can tell what I doing wrong here?