0

I am using Spring Data JPA and embedded HSQL. I have a LazyInitializationException inside a method annotated with @Transactional. I checked many forums but couldn't find any answer. So the code :

@Service
public class RepositoryServiceEntityService implements IServiceEntityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryServiceEntityService.class);

    @Resource
    private ServiceEntityRepository serviceEntityRepository;
    @Autowired
    private Converter converter;

    @Transactional
    public List<ServiceDTO> getServices() throws JsonParseException, JsonMappingException, IOException {
        LOGGER.debug("Getting the service list from DB");
        List<ServiceDTO> serviceDTOs = new ArrayList<ServiceDTO>();
        try {
            // getting the service entities
            List<ServiceEntity> serviceEntities = serviceEntityRepository.findAll();
            // converting them to ServiceDTOs
            for(ServiceEntity serviceEntity : serviceEntities) {
                serviceEntity.getEndpoints().size();
                serviceDTOs.add(converter.convertToServiceDTO(serviceEntity));
            }
            return serviceDTOs;
        } finally {
            LOGGER.debug("Retrieved {} services from DB", serviceDTOs.size());
        }
    }
}

The configuration:

<beans ...>

    <context:component-scan base-package="org.protneut.server.management.persistence.service" />

    <!-- **************** for JPA **************** -->
    <jpa:repositories base-package="org.protneut.server.management.persistence.repository"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean> 

    <jdbc:embedded-database id="hsqlDataSource" type="HSQL">
        <jdbc:script location="classpath:schema.sql" encoding="UTF-8" />
        <jdbc:script location="classpath:data.sql" encoding="UTF-8" />
    </jdbc:embedded-database>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="hsqlDataSource" />
        <property name="persistenceUnitName" value="hsql" />
        <property name="packagesToScan" value="org.protneut.server.management.persistence.model" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>

    ...
</beans>

And I have the following exception in RepositoryServiceEntityService when trying to call the size() on getEndpoints():

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.protneut.server.management.persistence.model.ServiceEntity.endpoints, could not initialize proxy - no Session

Likely I am not in the session?? I assume I made a mistake in configuration but not sure what.

Could somebody help please?

Thanks, V.

************************ UPDATE ************************

adding entity classes

@Entity
@Table(name = "SERVICE")
public class ServiceEntity implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    ...

    @OneToMany(fetch = FetchType.LAZY, targetEntity=EndpointEntity.class, mappedBy="serviceEntity")
    private List<EndpointEntity> endpoints;

    ...

}


@Entity
@Table(name = "ENDPOINT")
public class EndpointEntity implements Serializable {

    ...

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="SERVICE_ID")
    private ServiceEntity serviceEntity;

    ...

}
Viktor
  • 1,325
  • 2
  • 19
  • 41
  • just a guess, but your scanned package org.protneut.server.management.persistence.model doesn't seem like a package where one would create service classes, maybe your simply missing to scan the package with service classes – Master Slave Dec 05 '14 at 10:34
  • How do you use the result of this method? If it is serialized to JSON, some getters might be called and end with this exception. – Arnaud Denoyelle Dec 05 '14 at 10:54
  • possible duplicate of [Getting "could not initialize proxy - no Session" despite the fact I'm using a @Transactional annotation](http://stackoverflow.com/questions/16109170/getting-could-not-initialize-proxy-no-session-despite-the-fact-im-using-a) – Xstian Dec 05 '14 at 11:03
  • It is strange as if I omit dealing with the endpoints then it works... So the problem is to retrieve the endpoints in ServiceEntity. I'll add the entities to my post too. The exception coming from the service class and not from the contoller (also I convert the entity to DTO so I don't pass entity from the srvice class). Should I add the service class to a scan in configuration? But how come that the ServiceEntities can be queried? – Viktor Dec 05 '14 at 11:06

1 Answers1

0

I guess you didn't activate transaction management.

Add

<tx:annotation-driven/>

to your config file.

user3734130
  • 86
  • 1
  • 1
  • 6