Yurii
Yurii

Reputation: 1

Cascade Delete from DB, by some params("WHERE value=..."), using hibernate

In Bean class there is this annotation:

   class User {  
        @OneToMany(targetEntity = Feedback.class,mappedBy = "user",cascade =   
        CascadeType.ALL,fetch = FetchType.LAZY)  
    private List<Feedback> feedbacks;  
        ...  
    }

I want to delete user, which has some feedbacks. If I type this:

sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().get(User.class, id));

user will be deleted successfully, (id is primary key). But I want to delete all users, witch, have role="admin", and if i type this query:

String query = "DELETE from User WHERE role='" + role + "'";
    sessionFactory.getCurrentSession().createQuery(query).executeUpdate();

It will be delete only users without references to feedbacks. What wrong with my query? Please help.

Upvotes: 0

Views: 159

Answers (1)

Steve Ebersole
Steve Ebersole

Reputation: 9443

Nothing is wrong with your query. HQL delete queries do not "touch" associations. That is per JPA spec.

Check out this issue in Hibernate Jira about adding support for adding a new keyword CASCADE to delete queries for specifying associations which should also be deleted.

Upvotes: 1

Related Questions