Reputation: 5
I am noticing a weird behavior when I perform some basic checks using objects that have been .initialize()'ed using Hibernate.
The following 'if condition' fails even when it is supposed to pass:
for (int j = 0; j < trcList.size(); j++)
{
if (trcList.get(j).getABC().getId() == abc.getId())
{
//do something
break;
}
}
However if I change it slightly, it passes where expected. In the snippet below, I grab the LHS value in a local variable and use that for comparison:
for (int j = 0; j < trcList.size(); j++)
{
int x = trcList.get(j).getABC().getId();
if (x == abc.getId())
{
//do something
break;
}
}
trcList is an ArrayList created from an array of objects grabbed from a database using hibernate. Various fields in those objects including 'ABC' have been Hibernate.initialize()'ed.
Session session = null;
try {
session = HibernateUtil.initializeHibernateConnection(session);
Criteria cr = ... //specify search criteria
List results = cr.list();
TRC[] trcArray = new TRC[results.size()];
for (int i = 0; i < results.size(); i++) {
trcArray[i] = (TRC) results.get(i);
if (trcArray[i].getABC() != null)
{
Hibernate.initialize(trcArray[i].getABC());
}
}
session.getTransaction().commit();
return trcArray;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
Upvotes: 0
Views: 84
Reputation: 17622
I suspect trcList.get(j).getABC().getId()
is java.lang.Integer
and hence it should be compared with equals()
if (trcList.get(j).getABC().getId().equals(abc.getId())) {
}
Below test will assert the same
Integer i = new Integer(1); //set to 1
Integer j = new Integer(1); //also set to 1
System.out.println(i == j); //false, because it is reference comparison
System.out.println(i.equals(j)); //true
Upvotes: 2