Jothi
Jothi

Reputation: 15110

JOin the table in Query vs Lazy hibernate

I have disabled the Lazy fetching, and i joined the table in Criteria query. But after execution when i try to get the results, it is throwing error as lazy initialization is not done.

How do i resolve this issue?

public static String LST_LINEITEM_ANNUAL_ATT = "contractLineItem.lineitemAnnualAtt";
    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name="LINEITEM_ID",insertable=false,updatable=false)
    private Set<PLineitemAnnualAtt> lineitemAnnualAtt;

Criteria Query

List lstLineitemSublock = null;
        Criteria criteria = session.createCriteria(PContractLineitem.class, PContractLineitem.CLASS_ALAIS_NAME)
                //.createAlias(PContractLineitem.LST_LINEITEM_SUBBLOCK, PLineitemSubblock.CLASS_ALAIS_NAME)
                .createAlias(PContractLineitem.LST_LINEITEM_ANNUAL_ATT, PLineitemAnnualAtt.CLASS_ALAIS_NAME)
                ;
        this.setAttribute(criteria, restrictions);
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        lstLineitemSublock = criteria.list();

Upvotes: 0

Views: 68

Answers (2)

Consider specifying JoinType.LEFT_OUTER_JOIN in the createAlias method.

Changing createAlias(PContractLineitem.LST_LINEITEM_ANNUAL_ATT, PLineitemAnnualAtt.CLASS_ALAIS_NAME) to createAlias(PContractLineitem.LST_LINEITEM_ANNUAL_ATT, PLineitemAnnualAtt.CLASS_ALAIS_NAME, JoinType.LEFT_OUTER_JOIN) should help.

Regarding why it was not working with INNER JOIN, after doing some research I found this http://forum.spring.io/forum/spring-projects/data/35460-hibernate-createcriteria-question satisfactory.

That says:

When using an alias -defaulting to an inner join- the parent entity that the call returns has the joined collection uninitialized. Hibernate obviously discards the columns related to the collection data and when trying to access the collection another select occurs, generated by the mapping metadata, so it fetches the whole collection.

Upvotes: 1

mvlaicevich
mvlaicevich

Reputation: 103

Hi you can chage this:

@OneToMany(fetch = FetchType.LAZY, optional = false)

to:

@OneToMany(fetch = FetchType.EAGER, optional = false)

Also you can hack that, creating another criteria that return lineitemAnnualAtt list and set that to the Object you are returning on you original criteria.

Upvotes: 0

Related Questions