Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

native insert query in hibernate + spring data

I try to add the following code to a spring data jpa repository:

  @Query("insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)")
  void insertLinkToActivity(long commitId, long activityId);

But an app can't start with the exception:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: VALUES near line 1, column 59 [insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)]

Where am I wrong?

like image 335
mishka Avatar asked Jul 19 '14 19:07

mishka


People also ask

How execute native SQL query in Spring data JPA?

We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter.

What is native query in Spring data JPA?

Native queries are the most powerful and flexible way to implement your read operations. They enable you to use all features supported by your database, and Spring Data JPA handles almost all of the required boilerplate code.


2 Answers

I had to add nativeQuery = true to @Query

@Query(value = "insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)", nativeQuery = true)
like image 135
mishka Avatar answered Sep 24 '22 03:09

mishka


Use java object rather passing all parameters

@Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "insert into [xx_schema].[shipment_p] (gpn,qty,hscode,country_of_origin,created_date_time,shipment_id) "
            + "VALUES (:#{#sp.gpn},:#{#sp.qty},  :#{#sp.hscode} ,:#{#sp.countryOfOrigin}, :#{#sp.createdDateTime}, :#{#sp.id} )", nativeQuery = true)
    public void saveShipmentPRoducts(@Param("sp") ShipmentProducts sp);
like image 34
Santhosh Hirekerur Avatar answered Sep 26 '22 03:09

Santhosh Hirekerur