Hi, I'm new here. I googled quite a lot to find an answer to my problem, but haven't found one yet. I'm not sure it hasn't been asked (and answered) in one way or another, though.
I'm using an EJB to find customers in my data base according to certain criteria. The EJB method looks roughly like this:
Code:
public List findCustomers(parameters for the different criteria) {
Session session = HibernateUtils.currentSession();
Transaction tx = null;
List foundCustomers = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery(some HQL query);
foundCustomers = query.list();
tx.commit();
}
catch (HibernateException e)
{
if (tx != null) {
try {
tx.rollback();
}
catch (HibernateException e1)
{
}
}
throw e;
}
finally {
session.close();
}
return foundCustomers;
}
Now if I want to work with the found customers in some other class, Hibernate complains that the session is closed.
I read something about initializing, so I tried to apply it to my case, inserting the following code before the commit:
Code:
for (Iterator it = foundCustomers.iterator(); it.hasNext(); ) {
Customer theCustomer = (Customer) it.next();
Hibernate.initialize(theCustomer);
if (theCustomer.getAddresses() != null)
Hibernate.initialize(theCustomer.getAddresses());
}
In my model, every customer has a (possibly empty, possibly null) set addresses. Is there a way to avoid the second initialization? Maybe the
other class does not only want to use the customer's address, but other associated data as well.
Unfortunately the code addition above gives me a null pointer exception in the second initialization. theCustomer.getAddresses() can't be
null at this point of the code, so what's wrong?
I don't want to manipulate the found customer in the other class, I just want to read its data and some associated data (such as the addresses).
By the way: I'm working with Hibernate 3, Oracle 10.2.1, and JBoss 4.0.1 SP1.