Home > Enterprise >  Return empty collection when this collection is lazy intitialized
Return empty collection when this collection is lazy intitialized

Time:05-25

I have this object:

Entity

@Entity
public class someClass{
    private String name;
    private String labelKey;

    @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.LAZY)
    private Set<Product> products = new HashSet<>();
}

DTO

public class someClass{
    private String name;
    private String labelKey;
    private Set<Product> products = new HashSet<>();
}

My problem is that when I get this object but products are lazy initialized, when I mapp entity to DTO using Dozer, I get a LaziInitializedException, then i want to get that when I get products lazy initialized, this products will return a empry Set. Is this possible?

Thanks for your time and sorry for my english, it's not my native language.

CodePudding user response:

You could create/modify your Getter such that:

public Set<Product> getProducts() {
   if (products == null) {
       return new HashSet<>();
       //or products = new HashSet<>(), but I'm not sure of the side effects as far as database framework is concerned.
   }
   return products;
}

CodePudding user response:

Try marking your service class or method as @Transactional to let Spring handle session management.

public class ServiceUsingSomeClass {
    final SomeClassRepository someClassRepository;

    //Constructor ...
    
    @Transactional
    showProducts() {
       someClassRepository.findAll();
       // Do something with Set<Product>

    }
    
}
  • Related