Removing entities from another entity but not from database

Viewed 59

I have two entities: Player and Team:

Player:

@Data
@Entity
public class Player {
    @Column(nullable = false)
    private String username;

    @OneToOne
    @JoinColumn(name = "team")
    @JsonIgnore
    private Team team;
}

Team:

@Entity
@Data
public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToOne(fetch = FetchType.EAGER)
    private User captain;

    @OneToMany(fetch = FetchType.EAGER)
    private List<User> players;
}

TeamRepository:

@Repository
public interface TeamRepository extends JpaRepository<Team, Long> {
}

I want to delete the whole Team from database using delete() method from JPA. Unfortunately when I do so, all Players are also deleted from my database. I only want to detach them from the Team.

Adding cascade = CascadeType.ALL/DELETE to Team and calling delete() method results in User entities deletion from database, and that's what I don't want to happen.

Adding cascade = CascadeType.DETACH to Team and calling delete() throws me a

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`32308008_localdb`.`users`, CONSTRAINT `FKhn2tnbh9fqjqeuv8ehw5ple7a` FOREIGN KEY (`team_id`) REFERENCES `team` (`id`))

exception and I have no idea why.

If someone have an idea how to delete Team entity and detach User from context but not from database I would be VERY thankful!

0 Answers
Related