我在使用 JPA 时遇到了一些问题。我是这个话题的新手,所以我的问题可能真的很愚蠢,但我希望你们中的一些人能指出我正确的方向。
我有项目和用户实体。每个用户都可以有尽可能多的项目分配给他。我创建了双向关系
User OneToMany -> Project
,
Project ManyToOne -> User
我的问题是,如果我想删除一个用户,我也希望删除所有项目,但此时我收到一个错误:
Internal Exception: java.sql.SQLIntegrityConstraintViolationException:
DELETE on table 'USER_DATA' caused a violation of
foreign key constraint 'PROJECT_USERNAME' for key (Test Use1312r1).
The statement has been rolled back.
Error Code: -1
Call: DELETE FROM USER_DATA WHERE (USERNAME = ?)
bind => [1 parameter bound]
我的用户实体如下所示:
@Entity
@Table(name="USER_DATA", uniqueConstraints = @UniqueConstraint(columnNames = {"USERNAME", "link"}))
public class User implements Serializable {
@Column(name="USERNAME")
@Id
@NotNull
private String name;
@Column(name="USERROLE")
@Enumerated(EnumType.STRING)
private UserRole role;
private String password;
private String link;
// Should be unique
private String session;
@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Collection<Project> projects;
我的项目实体是这样的:
@Entity
@Table(name="PROJECT")
@XmlRootElement
public class Project implements Serializable {
@Id
private int id;
private String name;
private String description;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="START_DATE")
private Date beginDate;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="END_DATE")
private Date endDate;
@ManyToOne
@JoinColumn(name="USERNAME", nullable=false,updatable= true)
private User user;
还有我的 BL:
public User getUser(String userName) throws NoDataFoundException {
EntityManager em = DbConnection.getInstance().getNewEntity();
try {
User user = em.find(User.class, userName);
if (user == null) {
throw new NoDataFoundException("User is not found in the DB");
}
return user;
} finally {
em.close();
}
}
public void deleteUser(String userName) throws ModelManipulationException {
EntityManager em = DbConnection.getInstance().getNewEntity();
try {
User userToBeDeleted = getUser(userName);
em.getTransaction().begin();
userToBeDeleted = em.merge(userToBeDeleted);
em.remove(userToBeDeleted);
em.getTransaction().commit();
} catch (Exception e) {
throw new ModelManipulationException(
"Error in deleting user data for username" + userName
+ "with exception " +e.getMessage(),e);
}
finally{
em.close();
}
}
提前谢谢各位。