1

I have parent object with lots of child objects so cant use EAGER. I've tried multiple styles to get all the child objects of parent, but the below size code, and everything else i've tried throws

failed to lazily initialize a collection of role xxxx, could not initialize proxy - no Session

How do i initialize all the child objects ? do i really need to make another query for all of them. Seems kinda stupid.

    @Transactional
    public List<XXX> findYYYinXXX(Long id) {
        List<XXX> list = xxxRepo.findYYY(id);
        for (XXX p : list){
            p.getChild().size();
        }
        return list;
    }

Hibernate.initialize(p.getChild); used inside for loop also throws the same error

1
  • you can use Hibernate.initialize in your DAO layer and not in your service, in order to have session still opened Commented Sep 3, 2018 at 12:28

3 Answers 3

1

In your parent class use fetch type Eager.

1) use eager fetch type.

like @OneToMany(fetch = fetchType.Eager)

2) use join fetch query.

While creating query use fetch join.

eg. String hql = "select p from ParentClass p join fetch p.child_class_instance;

AS A SIDE MENTION: using @ElementCollections in this case at least requires using @CollectionTable(name="TABLENAME", schema = "SCHEMANAME")

Sign up to request clarification or add additional context in comments.

3 Comments

I'll try the second but the question literally starts with "I have parent object with lots of child objects so cant use EAGER."
try the second one and apply where condition in hql if require to filter the output.
Says it cant find table. Join seems to use camelcase table names tho. not sure why
1

If you are using lazy=extra the proxy collection is not initialized when calling size or isEmpty See this answer. You could get the first child instead of calling size.

However your question doesn't make sense because you want EAGER fetching but you are trying to force child loading. I think that what you really want is to make the client of this findYYYinXXX be part of the transaction as well, so if it needs to load the childs it will not fail.

Comments

1

if you are using spring-boot you can set the following property in you application.properties file to keep lazy loading:

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

1 Comment

Tried to put this in application.properties and into databaseConfig class, neither seem to have any impact. Still wont load child objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.