我有ManyToOne映射,我希望在删除Parent时删除所有子元素。不幸的是@OnDelete(action = OnDeleteAction.CASCADE)正在创建一个外键约束(在delete = restrict上),这是一个默认值。儿童餐桌。
实体类:
@Entity
@Table(name = "location_poc")
public class LocationPOC {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, unique = true)
private Integer id;
@Column(name = "contactname", nullable=false)
private String contactname;
@Column(name = "email", nullable=true)
private String email;
@Column(name = "phone", nullable=true)
private String phone;
@Column(name = "title", nullable=false)
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "locationID", referencedColumnName = "locationID")
@OnDelete(action = OnDeleteAction.CASCADE)
private Location location;
创建声明:
CREATE TABLE `location_poc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`contactname` varchar(50) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`title` varchar(50) NOT NULL,
`locationID` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `locationID_idx` (`locationID`),
CONSTRAINT `FK65jm2e3enqcu1nd37x48l57it` FOREIGN KEY (`locationID`) REFERENCES `location` (`locationID`),
CONSTRAINT `locationID` FOREIGN KEY (`locationID`) REFERENCES `location` (`locationID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
注意:删除级联约束是我在创建表和hibernate创建的其他约束时手动创建的约束。
我不知道为什么ondeleteaction.cascade不能正常工作。非常感谢任何帮助。
答案 0 :(得分:0)
自定义方言:
public class MySQLDialect extends MySQL57Dialect {
public MySQLDialect(){
super();
}
public boolean supportsCascadeDelete(){
System.out.println("--- supportsCascadeDelete() called.");
return true;
}
}
通过persistences.xml使用
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="..." transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="ORM.DBSubsystem.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>