9

I'm using spring-data-mongodb 1.2.0 with QueryDSL 2.9.0.

Why doesn't the QueryDslPredicateExecutor have a delete(Predicate predicate) method?

Is there a workaround?

John Willemse
  • 6,608
  • 7
  • 31
  • 45
Modi
  • 2,200
  • 4
  • 23
  • 37

3 Answers3

4

What you can probably do is this. With the predicate for "where" condition, query for the objects and then pass that to the delete method

QMyObj obj= new QMyObj("myObj");
Iterable<MyObj> myObjs = myObjRepository.findAll(obj.property.eq("property"));
myObjRepository.delete(myObjs);

Here I am first creating an instance of the Q class and then finding all the objects based on the predicate. Then calling the repository's void delete(Iterable<? extends T> entities) method.

May be it is because of this workaround they don't provide it, but that is for the Spring Source guys to confirm

Dhanush Gopinath
  • 5,652
  • 6
  • 37
  • 68
0

I was able to perform this by:

    @Autowired
    LocalContainerEntityManagerFactoryBean emFactory;
    
    EntityManager em;
    
    @PostConstruct
    private void setup(){
    em = emFactory.getObject().createEntityManager();
    }
    
        @Transactional private voide deleteByPredicate(Predicate predicate) { 
JPADeleteClause deleteClause = new JPADeleteClause(em, QPersonEntity.personEntity);
    em.joinTransaction();
    deleteClause.where(predicate).execute(); 
    }
  • This question is 8 years old!!!... and it already has a valid answer. Are you manually creating your own entity manager on a PostConstruct method?... Why are you doing this? – Iogui Aug 27 '21 at 02:20
  • The answer above didn't work for me.. Some people could run into the same problem as I did nowadays, that's all. Can't see the problem in that – Tomás Nunes Oct 04 '21 at 11:48
  • 1
    The fact that you are manually creating an entity manager in a PostConstruct method seems to me like a code smell. Observe that the question states that it is using spring data so one should probably be using a repository. If the @Dhanush Gopinath answer didn't work for you, maybe you did something wrong. It seems that you are reinventing the wheel here. Do you have another good motivation for manually creating an entity manager in this case? – Iogui Oct 04 '21 at 21:49
-1

using JPADeleteClause, pass two following parameters to it: entityManager and EntityPath QClass

QPersonEntity path = QPersonEntity.personEntity;
JPADeleteClause deleteClause = new JPADeleteClause(getEntityManager(), path);
deleteClause.where(path.name.eq("behrooz")).execute();
BehroOoz
  • 1
  • 3