Answer the question
In order to leave comments, you need to log in
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 :
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);
}
@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);
}
//......
@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;
}
//......
@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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question