这是我的情况。 3个实体:Customer,Address和CustomerAddress。我使用Hibernate的架构生成器来创建我的数据库表(正常和审计)。 客户与Address具有多对多关系,此关系由CustomerAddress实体定义。
客户类
@Entity
@Audited
public class Customer implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
@Audited(targetAuditMode = NOT_AUDITED)
@OneToMany(fetch=FetchType.LAZY)
@JoinColumn(name = "customerId", foreignKey = @ForeignKey(name="FK_CustomerToAddress_Customer"))
private List<CustomerAddress> addresses = new ArrayList<>();
}
地址类
@Entity
@Audited
public class Address implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
}
CustomerAddress Class
@Entity
@Audited
@Table(name = "CustomerToAddress")
@AssociationOverrides({
@AssociationOverride(name = "pk.customer",
joinColumns = @JoinColumn(name = "customerId")),
@AssociationOverride(name = "pk.address",
joinColumns = @JoinColumn(name = "addressId"))
})
public class CustomerAddress implements Serializable
{
@EmbeddedId
private CustomerAddressId pk = new CustomerAddressId();
...
}
CustomerAddressId Class
public class CustomerAddressId implements Serializable
{
@ManyToOne
private Address address;
@ManyToOne
private Customer customer;
...
}
现在,当我创建Customer,Address和CustomerAddress关系时,在我尝试执行删除之前,这一切都很棒。我可以删除一个CustomerAddress记录,但如果我尝试删除链接的地址记录,我会收到一个外键违规错误,如下所示:
DELETE语句与REFERENCE约束“FK_NAME”冲突。冲突发生在数据库“DB_NAME”,表“dbo.CustomerToAddress_AUD”,列'addressId'。
因此,CustomerToAddress_AUD表已经为Address表创建了一个FK,我将永远无法使用hibernate / JPA以编程方式删除地址。
有关如何创建经审核的多对多关系的任何想法都不会阻止链接实体的删除?
编辑: 导出架构的代码如下:
Configuration config = new Configuration();
// set connection properties on config
config.configure();
SchemaExport sexport = new EnversSchemaGenerator(config).export();
sexport.execute(false, true, false, true); // args: script, export, justDrop, justCreate