Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-data-jpa LazyInitializationException: no Session

i have a problem with Spring-data-jpa project.

JavaConfig file

...

@Configuration
@EnableJpaRepositories("it.myproject.data")
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
@PropertySource("classpath:/it/myproject/application.properties")
public
        class DBConfig
{

    private static final
            String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    @Resource
    private
            Environment environment;

    @Bean
    public
            DataSource dataSource()
    {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public
            EntityManagerFactory entityManagerFactory()
    {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public
            PlatformTransactionManager transactionManager()
    {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

To test that all works fine I created this method

@Transactional
    public
            void doIt()
    {
        PersonDTO created = new PersonDTO();
        created.setId(null);
        created.setFirstName("Pluto");
        created.setLastName("Paperino");
        Person pippo= repositoryPersonService.create(created);
        for (int i = 0; i < 10; i++) {
            BookDTO bookDTO = new BookDTO();
            bookDTO.setTitle("Fantasia" + i);
            bookDTO.setPerson(pippo);
            repositoryBookService.create(bookDTO);
        }
        repositoryPersonService.findAll().stream().forEach((Person t) -> {
            System.out.println(t.getBooks());
        });
    }

My entity is:

@Entity
@Table(name = "persons")
public
        class Person
        implements Serializable
{

    private static final
            long serialVersionUID = 198765467898765L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private
            Long id;
    @Column(name = "creation_time", nullable = false)
    @Temporal(javax.persistence.TemporalType.DATE)
    private
            Date creationTime;
    @Column(name = "first_name", nullable = false)
    private
            String firstName;
    @Column(name = "last_name", nullable = false)
    private
            String lastName;
    @Column(name = "modification_time", nullable = false)
    @Temporal(javax.persistence.TemporalType.DATE)
    private
            Date modificationTime;
    @OneToMany(fetch = FetchType.LAZY)
    private
            List<Book> books;
    @Version
    private
            long version = 0;

But i received this error message:

2014-04-09 12:31:54 TRACE LazyInitializationException:53 - failed to lazily initialize a collection of role: it.myproject.data.person.Person.books, could not initialize proxy - no Session org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: it.myproject.data.person.Person.books, could not initialize proxy - no Session

Can you help me? Thank you

like image 353
user3399743 Avatar asked Apr 09 '14 10:04

user3399743


People also ask

How do you fix org hibernate LazyInitializationException could not initialize proxy no session?

if you are using annotation configuration: add @Proxy(lazy=false) to all your entity classes. That's all about how to fix Exception in thread "main" org. hibernate. LazyInitializationException: could not initialize proxy - no Session.

How do I fix LazyInitializationException?

The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.

Why does JPA return duplicate rows?

The issue was that the wrong column in the Instrument Entity had the @ID attribute assigned to it. I removed it from User_ID and Added it to ID and it worked fine. But that will not result in repeated records while running your query right, so whatever records you have in DB has same values for User_ID ?

What is lazy proxy in Hibernate mapping?

Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement (via the excellent CGLIB library). By default, Hibernate3 generates proxies (at startup) for all persistent classes and uses them to enable lazy fetching of many-to-one and one-to-one associations.


2 Answers

Solved. I removed "(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)" from configuration and now it works fine. Thaks guys!

Before->

@Configuration
@EnableJpaRepositories("it.myproject.data")
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
@PropertySource("classpath:/it/myproject/application.properties")

Now ->

@Configuration
@EnableJpaRepositories("it.myproject.data")
@EnableTransactionManagement
@PropertySource("classpath:/it/myproject/application.properties")
like image 71
user3399743 Avatar answered Nov 16 '22 02:11

user3399743


It seems that @Transactional is not working, as repositoryPersonService.findAll() is returning a collection of detached entities. Then when trying to loop through those entities and access lazy initialized collections, we run into LazyInitializationException.

To confirm this, try putting a breakpoint in the method where findAll is called, and see if the transactional aspect is being applied or not.

To apply @Transactional to the test method, see that it's a Spring bean caught by a component scan (using ComponentScan("some.package") annotation).

like image 26
Angular University Avatar answered Nov 16 '22 01:11

Angular University