Samstag, 29. Juni 2013

Spring, JPA and Lazy fetch

Your task is to add a relation one-to-many to your entity class.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    List<Account> accounts;
}

Take a look on FetchType. In this case (LAZY) you have to fetch the collection in same session as the entity object. But Spring closes a session before. All you need is to implement a method in service layer and annotate it @Transactional(propagation=Propagation.REQUIRED). In such case Spring does all the operations inside the method in one session. For initialization just call some method (e.g. size()) on collection.

P.S.: Do NOT forget to switch on annotations in your configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       ">

    <!-- ... -->

    <tx:annotation-driven/>
    
    <!-- ... -->

</beans>

Keine Kommentare:

Kommentar veröffentlichen