Get lazy object with hibernation and JPA

how can i get a lazy object?

for example, I have a client table and a query table, then I create a project using sleep mode and JPA.

in the client table there is such a code

@OneToMany(cascade = CascadeType.ALL, fetch =FetchType.LAZY , mappedBy = "customer")
public Set<Request> getRequests() {
    return this.requests;
}

therefore, if a method is called from a client object getRequests(), it returns an empty object because it is lazy.

How can I do to get a lazy object without using annotation EAGER?

I saw that my problems depend on the session, because it is close. So, on the server side, I need to keep an open JPA session. How can i do this?

this is part of my applicationContext.xml, but it does not work:

<bean class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id="entityManagerFactory">
       <property name="persistenceUnitName" value="gestazPU"/>
   </bean>

   <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
       <property name="entityManagerFactory" ref="entityManagerFactory"/>
   </bean>

   <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

   <bean id="ebOpenEMinView" class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
       <property name="entityManagerFactory" ref="entityManagerFactory"/>
   </bean>

   <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>

   <bean id="TipoTicketDAO" class="it.stasbranger.gestaz.server.dao.impl.TipoTicketDAOImpl">
       <property name="entityManagerFactory" ref="entityManagerFactory" />
   </bean>
+3
source share
4 answers

Hibernate.initialize(lazyCollection) - , .

+5

, , , ? JPA .

JPA ( ), :

1) . , , , , , , .

2) , . getRequests() , , , .

PersistenceUtil.isLoaded(), , , , .

+1

Manager - " " .

0

Complete the set, call getId () or any object method. This should be done before the session closes, which means inside the transaction.

Standalone version of Hibernate

public Customer getCustomerWithRequest(Integer customerId){
    Session session = HibernateUtil.startTransaction();
    Customer = (Customer) session.get(Customer.class, customerId);
    List<Request> requests = customer.getRequests();
    for(Request rq:requests){
        rq.getId();
    }       
    session.close();
    return customer;
}

Spring / Hibernate | JPA version

@Transaction
public Customer getCustomerWithRequest(Integer customerId){        
    //get the requests and loop in here like above
}
0
source

All Articles