How to construct an insert query in JPA

后端 未结 3 1962
庸人自扰
庸人自扰 2021-01-04 23:33

I am trying to insert data into a table having columns (NAME, VALUE) with

Query query = em.createQuery(\"INSERT INTO TestDataEntity (NAME,          


        
相关标签:
3条回答
  • 2021-01-05 00:20

    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.

    0 讨论(0)
  • 2021-01-05 00:23

    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.

    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();
    
    0 讨论(0)
  • 2021-01-05 00:35

    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.

    0 讨论(0)
提交回复
热议问题