Using JPA entities in JSF. Which is the best strategy to prevent LazyInitializationException?

You should provide exactly the model the view expects. If the JPA entity happens to match exactly the needed model, then just use it right away. If the JPA entity happens to have too few or too much properties, then use a DTO (subclass) and/or a constructor expression with a more specific JPQL query, if … Read more

How to implement thread-safe lazy initialization?

If you’re using Apache Commons Lang, then you can use one of the variations of ConcurrentInitializer like LazyInitializer. Example: ConcurrentInitializer<Foo> lazyInitializer = new LazyInitializer<Foo>() { @Override protected Foo initialize() throws ConcurrentException { return new Foo(); } }; You can now safely get Foo (gets initialized only once): Foo instance = lazyInitializer.get(); If you’re using Google’s … Read more

Swift lazy instantiating using self

For some reason, a lazy property needs an explicit type annotation if its initial value refers to self. This is mentioned on the swift-evolution mailing list, however I cannot explain why that is necessary. With lazy var first: FirstClass = FirstClass(second: self) // ^^^^^^^^^^^^ your code compiles and runs as expected. Here is another example … Read more

How to solve the LazyInitializationException when using JPA and Hibernate

Hibernate 4.1.6 finally solves this issue: https://hibernate.atlassian.net/browse/HHH-7457 You need to set the hibernate-property hibernate.enable_lazy_load_no_trans=true Here’s how to do it in Spring: <bean id=”entityManagerFactory” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”> <property name=”dataSource” ref=”myDataSource”/> <property name=”packagesToScan” value=”com.mycompany.somepackage”/> <property name=”jpaVendorAdapter” ref=”hibernateVendorAdapter”/> <property name=”jpaDialect” ref=”jpaDialect”/> <property name=”jpaProperties”> <props> <prop key=”hibernate.enable_lazy_load_no_trans”>true</prop> </props> </property> </bean> Voila; Now you don’t have to worry about LazyInitializationException while navigating … Read more

Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans

The problem with this approach is that you can have the N+1 effect. Imagine that you have the following entity: public class Person{ @OneToMany // default to lazy private List<Order> orderList; } If you have a report that returns 10K of persons, and if in this report you execute the code person.getOrderList() the JPA/Hibernate will … Read more