S
S
Sland Show2018-09-21 18:51:26
Java
Sland Show, 2018-09-21 18:51:26

Why does the entity get a Lazy initialization error?

I have entities: Train and Seat. They are connected by a one-to-many relation.

Train

@Entity
@Table(name = "train")
public class Train {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "train", cascade = CascadeType.ALL)
    private Set<Seat> seats;
    ...
    // Геттеры и сеттеры


seat
@Entity
@Table(name = "seat")
public class Seat {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "carriage")
    private Integer carriage;

    @Column(name = "seat")
    private Integer seat;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "train_id", nullable = false)
    private Train train;
    ...
    // Другой код


When I try to get a train, I get an error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.slandshow.models.Train.seats, could not initialize proxy - no Session


What is the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yurii, 2018-09-21
@SlandShow

You have FetchType.EAGER initialized, not LAZY

D
drKred, 2018-09-21
@drKred

Hey! the problem is not lazy initialization, but judging by the error could not initialize proxy - no Session you have no session to connect to the database https://examples.javacodegeeks.com/enterprise-java...

V
Vladislav, 2018-09-24
@Div100

Sland Show
The Hibernate session is already dead, either make an Eager (which is not very good).
Or I use some kind of hb utility to manage the session.
Either in the service method through which you get this business - make it @Transactional read,
then it will have to take place in one session.
If it does not work, write - we'll figure it out

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question