Hibernate.initialize() to Initialize Proxy/Collection


#1

Hello,
I have employee entity and it is marked with cache annotation. However, when I execute I still see that below queries are triggered. I ensured that this entity is marked as LAZY in parent entities.

So after reading Vlad’s high performance guide, I realized to use Hibernate.initialize(Employee.class) so that I can get the lazy initialized data from proxy objects, however, still see the same issue.

Please guide me on this.

select
        emp0_.EMPNAME as EMPLOY1_27_1_        
    from
        EMPLOYEE emp0_     
    where
        emp0_.EMPID=?

select
        emp0_.EMPNAME as EMPLOY1_27_1_        
    from
        EMPLOYEE emp0_     
    where
        emp0_.EMPID=?

#2

We need to see the Hibernate configurations, the entity mappings and the code you are using.

Also, activate the SQL log in Hibernate so we can see what happens.


#3

Here are some of the properties used for caching


javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
hibernate.cache.use_query_cache=true
hibernate.query.plan_cache_max_size=2048

Also, my entity class looks like below. When ever, I call company.getEmployee() the queries mentioned in the question are getting triggered.

Hence, I am trying to call Hibernate.initialize(Employee.class) prior calling company.getEmployee() so that the queries are not getting generated to database, but from proxy.

@Entity
@Cacheable
@Table(name="COMPANY")
Class Company {
@OneToMany(mappedBy = "empid",fetch=FetchType.LAZY)
@BatchSize(size=1000)
private Set<Employee> employee;
 ...
 ...
}


#4

It’s not enough.

You need to set the CacheConcurrencyStrategy using the Hibernate-specific @Cache annotation:

@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

For more details, check out the User Guide.