0
Well I’m having a problem with my class at the Spring session
Error:
org.hibernate.LazyInitializationException: failed to lazily initialize
I have a class that represents object in session and 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(); }
// ...
}
Since 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 Template entity uses JPA spec annotation:
@Entity
public class Modelo extends BaseEntity<Long>{
@ElementCollection
private List<Price> prices = new ArrayList<>();
// ...
}
And within the Price Class contains :
@Embeddable
public class Price {
@Column(scale=2)
private BigDecimal value;
// ...
}
Good when calling the value of the price class in the view, kind of because it’s not @Embeddable(fetch = Fetchtype.EAGER) it can’t load for me by launching that Exception above, but how can I get around it using Hibernate’s LAZY DEFAULT?
VIEW a part where is launching 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 have tried to use the Abstractannotationconfigdispatcherservletinitializer using the filter to entityManager always stay open but it did not work very well not for me it persists the error do not know if it may be because I am using Thymeleaf or because I am using this in the wrong way filter used that way but it didn’t work.
public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Filter[] getServletFilters() {
return new Filter[]{
new OpenEntityManagerInViewFilter()
};
}
// ...
}
Ah I am using the following tools and frameworks in the Project
- Spring Boot (Security, MVC, DATA, etc)
- Thymeleaf
- Maven
Could someone help me.
Thank you from the start.
Hello, what is the specific reason to get around the problem using DEFAULT Lazy config from Hibernate? , why using a filter that even you haven’t tried can cause performance problems even worse than you setting fetch as Eager
– Leonardo Villela
So @Leonardovillela I’d just make JPA(Hibernate) search when necessary. And why would the filter be such a bad approach? 'Cause in some places they’re talking about using it so I can deal with Lazy inside Spring.
– Lucy Estela
I did not say that it would be a bad approach, but that it would bring some level of complexity, so if the use of Lazy were expendable, it would be unnecessary to use the filter, I will post an answer explaining how to deal with the filter :)
– Leonardo Villela