Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct an insert query in JPA

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:

  • What is wrong with the query string?

Many thanks.

like image 884
Armine Avatar asked Apr 11 '17 13:04

Armine


People also ask

What is the EntityManager method to insert data?

In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.

Can we write SQL query in JPA?

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.

What are three methods to execute queries in JPA?

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.


2 Answers

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.

like image 94
Máťa - Stitod.cz Avatar answered Sep 18 '22 20:09

Máťa - Stitod.cz


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.

like image 41
Armine Avatar answered Sep 18 '22 20:09

Armine