2

Here is my criteria:

public Commercial findManager(Entity entity) {
    DetachedCriteria criteria2 = DetachedCriteria.forClass(Role.class);
    criteria2.createAlias("workStation", "workStation");
    criteria2.createAlias("workStation.entity", "entity");
    criteria2.add(Restrictions.eq("entity.id", entity.getId()));
    criteria2.createAlias("commercial", "commercial", CriteriaSpecification.LEFT_JOIN);
    criteria2.setFetchMode("commercial", FetchMode.JOIN);
    criteria2.createAlias("commercial.function", "function");
    criteria2.add(Restrictions.eq("function.name", "MANAGER"));
    criteria2.setProjection(Projections.property("commercial"));
    Commercial commercial = (Commercial) getHibernateTemplate().findByCriteria(criteria2).get(0);
    return commercial;
}

This criteria works as intended except that it returns a proxy. Since I am going to query a lot of properties on that proxy I want to force hibernate to load that object in the same query, but even with fetchmode in JOIN mode it does not seem to work. What is wrong?

I use hibernate 3.3.2 and spring 2.5

Aldian
  • 2,481
  • 2
  • 24
  • 38
  • 1
    Are you sure that the returned instance, although a proxy, is not initialized? Take a look at this [answer](http://stackoverflow.com/a/32785467/4754790). – Dragan Bozanovic Feb 18 '16 at 18:21
  • 1
    You are right, after looking into your suggestion and making further investigation, I figured how that the proxy was actually initialized. – Aldian Feb 19 '16 at 09:29

1 Answers1

2

Thanks to Dragan, I figured out that the proxy was actually initialized. It was actually a bad interpretation of what I was seeing in the JDBC log and in the debugger.

I was seeing this:

Proxy with all fields null

But when looking deeper into it, I figured out that the data was there, and making logs into the console for the data did not trigger new calls to the database:

Proxy actually Initialized

After some more investigations I figured out that the FetchMode.JOIN and CriteriaSpecification.LEFT_JOIN in the original request are actually not needed to get this result. But the Adress field, which is a complex object, was not initialized, and querying on its attributes generated new requests to the database. Then I tried to add the following line and now it works like a charm (like in the previous screenshot where we can see that the adress field is a proxy)

    criteria2.setFetchMode("commercial.adresse", FetchMode.JOIN);
Aldian
  • 2,481
  • 2
  • 24
  • 38