D
D
Denis Kuznetsov2019-04-16 10:15:06
Java
Denis Kuznetsov, 2019-04-16 10:15:06

How to fix lazy initialization bug?

I have a table in which there is already a user, but he does not have cars, I want to take this user from the table and add a car to him, after updating the user's data in the table and pushing the car into the table of cars (he gets the user from the table successfully)
here error code :
5cb57f1ed66a2058221507.jpeg
here is main :

public static void main(String[] args) {
        UserService userService = new UserService();
        List<User> users = userService.findAllUsers();
        User user = users.get(0);
        System.out.println(user);
        Auto auto = new Auto("Bugatti", "Black");
        user.addAuto(auto); //вылетает тут 
        userService.updateUser(user);
    }

here is the user
@Entity
@Table (name = "f_users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int user_id;

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

    @Column(name = "user_age")
    private int age;

    //mappedBy --> field in class Auto
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Auto> autos;

    public void addAuto(Auto auto) {
        auto.setUser(this);
        autos.add(auto);
    }
//......

here is the car:
@Entity
@Table(name = "f_autos")
public class Auto {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int auto_id;

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

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "a_user_id") //a_user_id is foreign key
    private User user;

    public void setUser(User user) {
        this.user = user;
    }
//......

here is how the update happens if necessary
@Override
    public void update(User user){
        Session session = HibernateSessionFactoryUtil.getSessionFactory().openSession();
        Transaction tx1 = session.beginTransaction();
        session.update(user);
        tx1.commit();
        session.close();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Conacry, 2019-04-18
@DennisKingsman

You can use Hibernate.initialize().

Hibernate.initialize(user.getAutos);
user.addAuto(auto);

This will allow you to explicitly initialize the proxy object. If you have additional questions, write, I will be happy to help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question