Search code examples
javahibernatejpalazy-loadingeager-loading

Hibernate: How to fetch or load a lazy entity from another entity on base of particular condition?


I want to load "getBulla" in the following example but on the base of comparison with "getControl".

@OneToMany(mappedBy = "bullabase", fetch=FetchType.LAZY)
public Set<BullaBase> getbulla() {
   return this.bulla;
}

@Column(name = "Control", length = 40)
public String getControl() {
   return Control; //values: Mahidana, Gana, Funa, Khana, Bona, Nona, Raka, Tuka etc.
}

getControl contains 10 - 15 different static strings but bulla should be load on base of particular condition i.e Load all Entity and get Bulla entity only for control == "mahidana" and that too in single fetching


Solution

  • Dont think there is an out of the box solution but a workaround would be a wrap around method which would internally initialize the collection upon certain condition:

    public class CustomEntityRepo{
    
    
    
        public Entity findById(Long id){
    
            Entity entity = session.get(Entity.class, id);
    
            if(entity.getControl.equals(\* custom condition*\)){
                entity.getBulla.().size(); // init the collection
            }
    
            return entity;
        }
    
    }