簡體   English   中英

如何在 JPA 中構建插入查詢

[英]How to construct an insert query in JPA

我正在嘗試將數據插入到具有列(NAME, VALUE)的表中

Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (:name, :value)");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();

並得到以下異常:

ERROR org.hibernate.hql.internal.ast.ErrorCounter - line 1:42: unexpected token: VALUES 

此外,我也無法使用本機查詢插入記錄:

Query query = em.createNativeQuery("INSERT INTO TEST_DATA (NAME, VALUE) VALUES (:name, :value);");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();

正在拋出另一個異常:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement

問題是:

  • 查詢字符串有什么問題?

非常感謝。

我解決了這個問題。

根據

JPA中沒有INSERT語句。

但我可以用原生查詢來解決這個問題:我錯誤地提出了多余的問題; 在查詢結束時,通過刪除它解決了問題。

我找到了兩個例子,作者在本機查詢中使用插入( 第一個第二個 )。 然后,您的查詢可能是:

Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (?, ?)");
query.setParameter(1, name);
query.setParameter(2, value);
query.executeUpdate();

試試這個。

我能夠使用下面這樣做 - 我只有一個表名自行車有2個字段的id和名稱。 我使用下面的內容將其插入數據庫。

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();

對於手動創建的查詢,我們可以使用 EntityManager#createNativeQuery 方法。 它允許我們創建任何類型的 SQL 查詢,而不僅僅是 JPA 支持的查詢。 讓我們向存儲庫類添加一個新方法:

@Transactional
public void insertWithQuery(Person person) {
    entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)")
      .setParameter(1, person.getId())
      .setParameter(2, person.getFirstName())
      .setParameter(3, person.getLastName())
      .executeUpdate();
}

使用這種方法,我們需要定義一個包含列名稱的文字查詢並設置它們對應的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM