John R. :
I am new in hibernate and I am struggling with a problem. I want to display a list of objects to a .XHTML page using JSF. But I don't know why, I lose the data on the way. Even though the method from DAO returns a list of objects from database (I saw it by doing debug) when I try to assign that list to a list of users from another class I loose that data and the list from DAO becomes null. So there are no results in GUI from my datatable.
public class UsersBean {
private List<User> allUsers;
public UsersBean() {
init();
}
private void init() {
UsersController.doInitialise(allUsers);
}
// getters, setters
}
public class UsersController {
public static void doInitialise(List<User> users) {
users = new ArrayList<User>();
UserDao userDao = new UserDaoImpl();
users = userDao.getAllEnities();
System.out.println(users.toString());
}
}
public class UserDaoImpl{
@Override
public List<User> getAllEnities() {
List<User> users= null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("from User");
users= query.list();
transaction.commit();
} finally {
session.close();
}
return users;
}
}
Alex Somai :
You are not assigning the value of allUsers
into your UsersBean
, probably that's why is not working. To have it working, refactor the doInitialise
to return a List<User>
, then, in the UsersBean
, just assign the users.
class UsersBean {
private List<User> allUsers;
public UsersBean() {
init();
}
private void init() {
this.allUsers = UsersController.doInitialise();
}
}
public class UsersController {
public static List<User> doInitialise() {
UserDao userDao = new UserDaoImpl();
return userDao.getAllEnities();
}
}