I have many-to-one relationship between Answer and Topic. My Answer looks as :
Answer has hashcode and equals based on answer_id. There is no toString().
The problem is when I call method load() to get hibernate proxy of Answer , it loads immediately all Answer's and Topic's and JuniorUser's properties.
What causes hibernate to load all properties and even associations immediately?
BTW, I set breakpoint just after this method is called and see all queries generated by hibernate in my console.
You can't lazy load a non-collection mapped entity unless you set optional=false. This is because Hibernate doesn't know if there should be a proxy there or a null, unless you tell it nulls are impossible. If you do not do this than Hibernate must eagerly load the entity to determine if a proxy can be created or not.
You can remove @NotFound(action = NotFoundAction.IGNORE) as well.
I tried your suggestion and changed my mapping as follows in Answer entity:
optional = false is right thing to lazy load but it did not help in my case, I also added @LazyToOne(PROXY) but it did not help as well!
Don't you know what else can cause my related entities to be loaded together with answer ?
I think method load(entityClass,Id) should not go to db immediately but only when property other than id is requested. But I do only this :
It still causes my Answer's properties, related Topic's and JuniorUser's properties to be selected from database.
Hibernate logs these queries as well as values and values are real values from my db whatever answerId I provide.
Never use @Access(AccessType.PROPERTY))!!! Because you will be fed up with queries generated by hibernate.
And really as last stupid attempt to solve this I changed @Access to AccessType.FIELD. Amazingly hibernate produced only one query to fetch only my answer but not single ended associations. Of course this is also thanks to FetchType.LAZY and optional=false .
The truth is that AccessType.PROPERTY is really dangerous and must be avoided! This implies not only to single ended associations but also to collection ended association. This tutorial explains one more decent pitfall with @AccessType.PROPERTY in detail.
I rarely ever use the access type annotation at all. I annotate my fields not my getters and I omit that annotation altogether. For that reason I had never actually run into that. I am glad you got it figured out!. Thanks for posting back with your solution.