1

We have a weird LazyInitializationException with an entity and a JPA repository. However, as you can see, the entity is ultra simple :

@Entity
@Table(name = "USERS")
@Getter
@Setter
@NoArgsConstructor
public class UserEntity {

    @Id
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name = "NAME", length = 50)
    private String name;
}

It is fetched with a JPARepository :

@Repository
public interface UserEntityRepository extends JpaRepository<UserEntity, Long> {

}

// At some other point
final userEntity userEntity = userEntityRepository.getOne(order.getUserId());

However, using just getName() on the entity provokes LazyInitializationException :

userEntity.getName();

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:155)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:268)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
    at application.UserEntity_$$_jvst303_3.getName(UserEntity_$$_jvst303_3.java)
    at application.OrderConverter.from(OrderConverter.java:42)

I can see that the entity has been replaced by a proxy, but why has it been replaced by a proxy at this point ? There is no relationship in the entity.

Thanks for any help.

Kamalen
  • 766
  • 6
  • 21
  • short answer: use findOne instead of getOne, as getOne will return a proxy of the entity instead of loading it. – Zeromus May 08 '18 at 14:12
  • Indeed, I have replaced the method with findById (seems our dependencies have been upped to spring-data-commons-2.0.5, and findOne seems to be overwritten by a QueryByExampleExecutor interface I don't know about yet) and it is now working. Thanks. – Kamalen May 08 '18 at 14:23

0 Answers0