Hibernate Persistence cascade = CascadeType.Remove获取约束违规错误

时间:2015-03-21 16:09:03

标签: hibernate spring-mvc jpa

我在User和Property Table之间有@oneToMany映射,user_id作为属性表中的外键。现在我希望管理员删除用户后立即删除相应的属性。

我单独尝试了cascade = CascadeType.REMOVE和orphanRemoval = true,但我得到了ConstraintVoilation Exception。在阅读了其他开发人员的建议后,最后我的代码如下,请帮助我......

User.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;

Property.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数据库,用户有属性映射。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好的,所以我几乎在我的程序中做同样的事情,它工作正常。让我告诉你代码

在你的用户表中(会更好的是用户,用户在大多数SQL中已经是保留字)

@JsonIgnore
@OneToMany(mappedBy = "users", fetch = FetchType.EAGER, cascade =  CascadeType.REMOVE)
private Set<Property> property;

在属性表

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "users")
private Users users;

它在我的项目中运作良好。