Java 如何在 JPA 中构建插入查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43347602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to construct an insert query in JPA
提问by Armine
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.
非常感谢。
采纳答案by Armine
回答by Má?a - Stitod.cz
I found two examples where the author uses the insert in a native query (firstand second). Then, your query could be:
我发现了两个例子,作者在本机查询中使用插入(first和second)。然后,您的查询可能是:
Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (?, ?)");
query.setParameter(1, name);
query.setParameter(2, value);
query.executeUpdate();
Try this.
尝试这个。
回答by Rajdeep Singh
I was able to do this using the below - I just had a Table name Bike with 2 fields id and name . I used the below to insert that into the database.
我能够使用下面的方法来做到这一点 - 我只有一个表名 Bike 有 2 个字段 id 和 name 。我使用以下内容将其插入到数据库中。
Query query = em.createNativeQuery("INSERT INTO Bike (id, name) VALUES (:id , :name);");
em.getTransaction().begin();
query.setParameter("id", "5");
query.setParameter("name", "Harley");
query.executeUpdate();
em.getTransaction().commit();