Problem with Fetch Lazy [Spring Boot] [Thymeleaf]

0

Well I have a problem with my class that is in the Spring session Error:

org.hibernate.LazyInitializationException: failed to lazily initialize  

I have a class that represents object in session and it is annotated:

@Component
@Scope(value="session", proxyMode= ScopedProxyMode.TARGET_CLASS)
public class Test{
   private Map<Item, Long> items = new LinkedHashMap<>();
   public Colletion<Item> getList() { return items.keySet(); }
   // ...
}

Being that it has an Item LinkedHashMap that looks like this:

public class Item {
   private Modelo modelo;
   // Esse metodo retorna uma Soma de Value da Classe Price
   public BigDecimal getPrice() { return modelo.valorSomado(); }
   // ...
}

Which in turn is my entity Model uses JPA spec annotation:

@Entity
public class Modelo extends BaseEntity<Long>{
   @ElementCollection
   private List<Price> prices = new ArrayList<>();
   // ...
}

And within the Price Class it contains:

@Embeddable
public class Price {
   @Column(scale=2)
   private BigDecimal value;
   // ...
}

of hibernate?

VIEW a part where you're throwing the error:

<tr th:each="item : ${beans.test.list}">        
    <td th:text="${item.modelo.title}" /> <!-- Até aqui funciona -->
    <td class="numeric-cell" th:text="${item.price}"/> <!-- Aqui Lança um erro -->

I've tried using the AbstractAnnotationConfigDispatcherServletInitializer using the filter for entityManager to always stay open but it did not work very well not for me it persists the error I do not know if it could be because I'm using Thymeleaf or because I'm using this filter incorrectly I used it that way but it did not work.

public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
  @Override
  protected Filter[] getServletFilters() {
    return new Filter[]{ 
       new OpenEntityManagerInViewFilter()
    };
  }
  // ...
}

Ah I'm using the following tools and frameworks in Project

  • Spring Boot (Security, MVC, DATA, etc.)
  • Thymeleaf
  • Maven

Someone could help me. I'm grateful right now.

    
asked by anonymous 27.06.2016 / 02:47

1 answer

0

Hello, as we talked in the comments, one possible solution is to write down your method getList with @Transactional of Spring, so your method will run within a transaction avoiding this problem, code would be something like: p>

@Component
@Scope(value="session", proxyMode= ScopedProxyMode.TARGET_CLASS)
public class Test{
   private Map<Item, Long> items = new LinkedHashMap<>();

   @Transactional(readOnly = true)
   public Colletion<Item> getList() { return items.keySet(); }
   // ...
}

Note: There may be some problems if you do not have a configuration for transaction use, if this is the case write in the comments I teach you how to do.

    
02.07.2016 / 03:35