gpt4 book ai didi

java - Spring Data JPA 奇怪的行为

转载 作者:行者123 更新时间:2023-12-02 11:42:21 24 4
gpt4 key购买 nike

我是 JPA 和 Hibernate 的新手,遇到了奇怪的行为。考虑下面的代码。

许可证实体:

@Entity
@Data
public class License {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Enumerated(EnumType.STRING)
private LicenseType type;
@Column(unique = true)
private String activationKey;
@OneToMany(mappedBy = "id", cascade = CascadeType.REMOVE)
private List<Payment> payments = new ArrayList<>();
private long productId;
private String productName;
private long term;
private long creationTimestamp;
private boolean active;
}

LicenceType 枚举:

public enum LicenseType {
NAMED
}

付款实体:

@Entity
@Data
public class Payment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH})
private License license;
private BigDecimal sum;
}

LicenceRepository:

@Repository
public interface LicenseRepository extends CrudRepository<License, Long> {

}

PaymentRepository:

@Repository
public interface PaymentRepository extends CrudRepository<Payment, Long> {

}

引导类:

@SpringBootApplication
public class LsPocApplication {

public static void main(String[] args) {
SpringApplication.run(LsPocApplication.class, args);
}

@Bean
public CommandLineRunner demo(LicenseRepository licenseRepository, PaymentRepository paymentRepository) {
return (args) -> {

License license = new License();
license.setActivationKey(UUID.randomUUID().toString());

Payment payment = new Payment();
payment.setSum(BigDecimal.valueOf(new Random().nextDouble()));
payment.setLicense(license);

paymentRepository.save(payment);

// licenseRepository.delete(license); // This does nothing
// licenseRepository.delete(license.getId()); // This deletes both licence and associated payment(s)
};
}
}

所以问题是为什么 licenseRepository.delete(license.getId()) 按预期工作,但 licenseRepository.delete(license) 不执行任何操作?我认为,它们在逻辑上是等效的。还是我错了?

请指教。

提前致谢!

最佳答案

您的许可证是否实现了可序列化?如果是这样,我认为这两个调用将调用相同的方法,即用于 id 参数的方法。但由于没有许可证有另一个许可证作为 id,因此不会删除任何内容。

原因是,在类型删除之后,所有剩下的漂亮泛型对于 id 来说都是Serialized,对于实体类型来说都是Object。如果实体类型也恰好实现了 Serialized,则使用该方法,因为它更具体。 (我不得不承认我的大脑里有一些挥手的 Action ,但这个想法应该是正确的)。

这就是为什么从 Spring Data 2.0(又名 Kay)开始更改方法名称的原因,因此这种困惑不会再发生。

关于java - Spring Data JPA 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com