Pregunta

I am having some problems with JPA. I am new at this topic so my question maybe is really stupid, but i hope some of you could point me to the right direction.

I have Project and User entity. Every user can have as many projects assign to him as it can. I created the relationship bidirectional User OneToMany -> Project, Project ManyToOne -> User

My problem is that if i want to delete a user i want all the projects to be deleted as well, but i receive an error at that point:

 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]

My User entity looks like this:

@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;

My Project Entity like this:

@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;

And my 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();
    }
}

Thanks in advance guys.

¿Fue útil?

Solución

after the merge call, are there any Projects in userToBeDeleted.projects? I suspect there are none, which prevents any from being deleted. Cascade remove can only work if you populate both sides of bidirectional relationships, so check that when you associate a user to a project, you also add the project to the user's project collection.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top