javaspringdatabaseentity

User cannot be deleted from the database


The goal is to check and delete the user's card when they are deleted, provided it is no longer in use. This is the format for user deletion:

@Transactional
public void deleteUserById(long userId) {
    User user = userRepository.findById(userId);
    if (user == null) {
        throw new IllegalArgumentException("User with id " + userId + " not found");
    }
    userRepository.deleteById(userId);
}

In this format, the user is deleted only when the 'if' condition is met, meaning when the card belongs solely to the user being deleted. However, if the card belongs to more than one user, the code executes correctly, but the user is not deleted from the database. What could be the reason for this?

@Transactional
public void deleteUserById(long userId) {
    User user = userRepository.findById(userId);
    if (user == null) {
        throw new IllegalArgumentException("User with id " + userId + " not found");
    }
    if (userBankCardService.checkBankCardUsers(user.getUserBankCard().getCardNumber()) == 1) {
        userBankCardService.deleteBankCard(user.getUserBankCard().getCardNumber());
    }
    userRepository.deleteById(userId);
}

If it's important, here are my entities.

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@ToString(exclude = "users")
@Table(name = "users_bank_cards")
public class UserBankCard {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "card_number")
    private long cardNumber;
    @Column(name = "cvv")
    private short cvv;
    @Column(name = "card_expiration_date")
    private String cardExpirationDate;
    @OneToMany(mappedBy = "userBankCard", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<User> users = new ArrayList<>();
}

 @Entity
 @AllArgsConstructor
 @NoArgsConstructor
 @Data
 @Builder
 @ToString(exclude = {"subscription"})
 @Table(name = "users")
 public class User {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private long id;
     @Column(name = "phone_number")
     private long phoneNumber;
     @Column(name = "password")
     private String password;
     @Column(name = "auto_renew")
     @Enumerated(EnumType.STRING)
     private AutoRenewStatus autoRenew;
     @Column(name = "end_time")
     private LocalDateTime endTime;
     @Column(name = "email")
     private String email;
     @ManyToOne
     @JoinColumn(name = "bank_card_id")
     private UserBankCard userBankCard;
     @ManyToOne
     @JoinColumn(name = "subscription_id")
     private Subscription subscription;
 }

How can I delete a user when it's not necessary to delete the card?


Solution

  • probably there is foregin key. try to delete user by yourself direct in the database, and check if there is any error. In my case hibernate won't throw any exception about that.