0

I use spring boot, and I want to add 1 year to a specific column in mysql database

String queryRecherche = "UPDATE myTable t SET t.dateDebut = DATE_ADD(t.dateDebut, INTERVAL 1 YEAR) WHERE.id = 3 ";
Query query = em.createQuery(queryRecherche);;
query.executeUpdate();

But I get the folowing error :

org.hibernate.query.sqm.ParsingException: line 1:66 no viable alternative at input 'DATE_ADD(t.dateDebut,INTERVAL1'

Have you please any suggestions to do this.

1
  • 2
    createQuery is for JPQL, you want createNativeQuery instead. Commented Jan 19, 2023 at 9:13

2 Answers 2

1

You're using Hibernate 6 (I can tell by the error message), so the correct HQL syntax to use is:

UPDATE MyEntity t SET t.dateDebut = t.dateDebut + 1 year WHERE t.id = 3

You had three errors in your query:

  1. You referred to the name of a table instead of the name of an entity class in the UPDATE clause.
  2. You used the unportable MySQL DATE_ADD function instead of the portable HQL date/time arithmetic described here.
  3. The syntax of your WHERE clause was garbled.

Perhaps you meant for this to be a native SQL query, in which case you called the wrong method of Session. But there's no need to use native SQL for the above query. As you can see, HQL is perfectly capable of expressing that query.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use SQL directly, via createNativeQuery, or register a new function as shown in this example to call it from HQL

1 Comment

He doesn't need to register a function here because he's using H6 which has built-in support for date/time arithmetic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.