Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jakarta.persistence.TransactionRequiredException: Executing an update/delete query

I use spring boot 3.0.0, I try to use query.executeUpdate() method .

There is my code:

@Transactional
public void UpdatePassageByNiveau(int niveau, String cin) {
    String queryRecherche = "UPDATE Passage p SET p.dateDebut = p.dateDebut + 1 year, "
            + "p.dateFin = p.dateFin + 1 year WHERE resident.cin = :cin and p.niveau = :niveau ";
    Query query = em.createQuery(queryRecherche);
    query.setParameter("cin", cin);
    query.setParameter("niveau", niveau);
    query.executeUpdate();
}

I use the annotation @Transactional from org.springframework.transaction.annotation.Transactional. But it didn’t work, and i steal have this error : jakarta.persistence.TransactionRequiredException: Executing an update/delete query|.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This error typically occurs when we’re trying to perform a database operation that modifies the database without a transaction.

The obvious solution is to wrap any database-modifying operation in a transaction:

Transaction txn = session.beginTransaction();
Query query
  = session.createQuery("UPDATE Passage p SET p.dateDebut = p.dateDebut + 1 year, "
            + "p.dateFin = p.dateFin + 1 year WHERE resident.cin = :cin and p.niveau = :niveau ");
    query.setParameter("cin", cin);
    query.setParameter("niveau", niveau);
updateQuery.executeUpdate();
txn.commit();

In the code snippet above, we manually initiate and commit the transaction. Although in a Spring Boot environment, we can achieve this by using the @Transactional annotation.

@Service
@Transactional
public class FooService {
    //...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading