【发布时间】:2018-01-26 12:43:26
【问题描述】:
我是 JPA 和 Hibernate 的新手,遇到了奇怪的行为。考虑下面的代码。
License实体:
@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
}
Payment实体:
@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) 什么都不做?我假设,它们在逻辑上是等价的。还是我错了?
请指教。
提前致谢!
【问题讨论】:
-
如果您将 License id 从原始 long 更改为 Long 类,也会发生同样的情况吗?
-
@arocketman 是的
-
@alxg2112 尝试从关系映射中删除级联并检查它。
-
@chŝdk 没有级联,一切正常。为什么这对他们不起作用,这就是问题......
-
@alxg2112 当您删除 Cascade 时它会起作用,但为什么呢?老实说我不知道,我已经在网上挖了一段时间了,我还没有找到答案,请查看this thread 以供参考。
标签: java spring hibernate spring-data-jpa