简体   繁体   中英

Hibernate One to Many relation- Child table not updating

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);

}

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM