目标是在用户的卡被删除时检查并删除该卡,前提是该卡不再使用。这是用户删除的格式:
@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);
}
在此格式中,仅当满足“if”条件时才会删除用户,即该卡仅属于被删除的用户。但是,如果该卡属于多个用户,则代码可以正确执行,但不会从数据库中删除该用户。这可能是什么原因?
@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);
}
如果很重要,这是我的实体。
@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;
}
不需要删除卡的情况下如何删除用户?
可能有外键。尝试直接在数据库中自行删除用户,并检查是否有错误。就我而言,休眠不会抛出任何异常。