I am trying to insert data into a table having columns (NAME, VALUE) with
Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (:name, :value)");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();
and getting the following exception:
ERROR org.hibernate.hql.internal.ast.ErrorCounter - line 1:42: unexpected token: VALUES
Also, I cannot insert a record using a native query either:
Query query = em.createNativeQuery("INSERT INTO TEST_DATA (NAME, VALUE) VALUES (:name, :value);");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();
Another exception is being thrown:
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
The question is:
Many thanks.
In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.
It supports both JPQL and SQL queries, and the query that is specified by using the @Query annotation precedes all other query generation strategies. Let's find out how we can create both JPQL and SQL queries with the @Query annotation.
There are three basic types of JPA Queries:Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax. Criteria API Query, constructed programmatically via different methods.
I found two examples where the author uses the insert in a native query (first and second). Then, your query could be:
Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (?, ?)");
query.setParameter(1, name);
query.setParameter(2, value);
query.executeUpdate();
Try this.
I solved the issue.
According to this,
There is no INSERT statement in JPA.
But I could solve the issue with native query: I have mistakenly put a redundant ; at the end of the query, so the issue solved by removing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With