1
Good night,
I am trying to create a method that receives any entity class and an ID to start a session on Hibernate. The idea is to make a Generic DAO to take only the ID of the entities I want.
Follow the code I’m trying to make:
public class GenericDAO<T> {
public T getEntity(T entity, int id){
Session session = null;
Object result = null;
try {
session = PoliGenericDAO.getSessionFactory().openSession();
Criteria crit = session.createCriteria("AQUI VEM A CLASSE GENERICA".class);
result = crit.uniqueResult();
} catch (Exception e) {
System.out.println("getBasic.GenericClass.Error: " + e);
}finally {
session.close();
}
return null;
}
}
My code to catch a user with an ID x is the second:
teamModel.getUserList().add(userDao.getUserById(user.getId()));
And I’d like it to stay that way:
teamModel.getUserList().add(genericDao.getEntity(Entity, user.getId()));
NOTE: Where in this case, 'Entity' would be the User class
The idea here is to make the minimum of queries to the bank possible, since using my current method, I have as return of the bank, the complete entity, that in this case I n need.
But how do you ensure that all passed objects will have the Id attribute if they are generic? I believe that what you should do is declare an interface with the necessary attributes/methods, implement this entity in its entities, and then receive objects that implement such an interface in
getEntity
– Andre
The right way is to have your entities standardized, create an abstract class
BaseEntity
for example containing the id, all entities will derive from it. In itsGenericDAO
you can then indicate thatT extends BaseEntity
, solving the problem pointed out by @user140828– nullptr
Thank you @ngueno, I’ll try it this way.
– Arthur Santos