【发布时间】:2015-03-21 16:09:02
【问题描述】:
我在用户和属性表之间有@oneToMany 映射,其中 user_id 作为属性表中的外键。现在我希望管理员删除用户后,相应的属性也将被删除。
我单独尝试了 cascade = CascadeType.REMOVE 和 orphanRemoval=true,但我得到了 ConstraintVoilation 异常。在阅读了其他开发人员的建议后,最后我的代码如下,请帮助我...
用户.java:
@OneToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},mappedBy ="user",orphanRemoval=true)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.MERGE,
org.hibernate.annotations.CascadeType.PERSIST,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN
})
private List<Property> properties;
属性.java:
@Entity
public class Property implements Serializable {
@Id
@GeneratedValue()
private int id;
private String name;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
删除用户时的错误是:
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`realestate`.`Property`, CONSTRAINT `FK_77bnqf5go6cydttxwtiig6i9a` FOREIGN KEY (`user_id`) REFERENCES `User` (`userId`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
我正在使用 Mysql 数据库并且用户有属性映射。
感谢您的帮助。
【问题讨论】:
-
也让我帮助您提高声誉。我也一直在负面回购.. 真的 s****
标签: hibernate spring-mvc jpa