Hibernate One to Many relation- Child table not updating

Viewed 319

Here I am adding a list of new orders to a specific user. While adding orders to a specific user, it returns success status, but still my database is empty. Why the data is not getting added...?

Users

@Entity
Class Users{

@Id
private int id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Orders> orders;

}

Orders

@Entity
Class Orders{

 @Id
 private int id;

 private Date orderDate;

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "user_id")
 private User user;
}

Repository

public ResponseEntity<String> addOrder(int userId,List<Orders> orders) throws UserNotFound{
        User user =userRepository.findById(userId).orElse(null);
        if(user==null) throw new UserNotFound("User Not Found");
        for(Orders o:orders){
            o.setOrderDate(new Date("....."));
        }
        user.getOrders().addAll(orders);
       userRepository.save(user);

}

1 Answers

Try to add cascade persist to your relation specification:

@Entity
Class Users{

@Id
private int id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade={CascadeType.PERSIST})
private List<Orders> orders;

}
Related