public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long userId;
String name;
@OneToMany(cascade = CascadeType.REMOVE)
List<Player> playerList = new ArrayList<>();
}
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long playerId;
String team;
@ManyToOne
User user;
}
User can have multiple players.
I want to delete a single player i.e. reference from player table[1 entry], user_player[1 entry] table .
Please help, how can i do it without using HQL.
User u = new User();
u.name = "George";
Player p1 = new Player();
p1.team = "india";
Player p2 = new Player();
p2.team = "us";
session.beginTransaction();
session.save(u);
session.save(p1);
session.save(p2);
session.getTransaction().commit();
now i want to delete p1, but if i use session.delete then one reference in user_player table is left. I don't want to delete the whole user. Thanks for response
If you change your cascade to cascade-all this all becomes simpler. You have an aggregate object, and you should only perform database operations on the aggregate root, which in your case is User. So, you should add and remove players from User, and save only that. The save will then cascade to the players. If you remove the player from the user, then save the user, the player will be deleted by hibernate for you. To make this work, you have to have an addPlayer(Player player) method in your User class which adds the player to the collection, and a setUser(User user) method on your Player class, which is called from within addPlayer().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With