Setting FetchMode in native Hibernate

I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.

Currently, I have something like:

Session s = HibernateUtil.getSessionFactory().openSession();
MyClass c = (MyClass)session.get(MyClass.class, myClassID);


Asked by: David942 | Posted: 21-01-2022






Answer 1

You could try something like this: (code off the top of my head)

Criteria crit = session.createCriteria(MyClass.class);
crit.add(Restrictions.eq("id", myClassId));
crit.setFetchMode("myProperty", FetchMode.EAGER);
MyClass myThingy = (MyClass)crit.uniqueResult();

I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.

Answered by: Blake474 | Posted: 22-02-2022



Answer 2

If you're not using Criteria there's also the JOIN FETCH keyword that will eagerly load the association specified by the join.

session.createQuery("select p from Parent p join fetch p.children c")

Answered by: Michelle851 | Posted: 22-02-2022



Answer 3

There is a static initialize(Object) method in the Hibernate main class. You could use that to force loading of your collection:

MyClass c = (MyClass)session.get(MyClass.class, myClassID);
Hibernate.initialize(c.getMySetOfMyClass2());

However, a default value of lazy fetching is just that: a default value. You probably want to override the laziness in the mapping for your particular Set.

Answered by: Aldus377 | Posted: 22-02-2022



Similar questions

java - FetchMode as JOIN in JPA

How do we specify FetchMode as JOIN in JPA? I do understand that in hibernate we can do it by @Fetch(FetchType.JOIN). But how do we achieve this in JPA?


java - How does the FetchMode work in Spring Data JPA

I do have a relation between three model object in my project (model and repository snippets in the end of the post. When I call PlaceRepository.findById it does fire three select queries: ("sql") SELECT * FROM place p where id = arg SELECT * FROM user u where u.id = place.user.id SELECT * FROM city c LEFT OUTER JOIN state s on c....


java - FetchMode Subselect not running on Set attribute

My class has a Set collection attribute and it's marked with @Fetch(value = FetchMode.SUBSELECT). But it is still loading the attribute with different queries instead of just one with subselect @Entity @Table(name = "NPRO_USUARIOS") public class User implements Serializable { //Method and atributes supressed @ManyToMany(cascade ...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top