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|
.
CodePudding user response:
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 {
//...
}