4

I am migrating my spring mvc codebase to Spring Boot based Rest APIs, earlier we were using jdbcTemplate and writing sql queries for almost everything. But now we have started using Spring Data JPA and life is easy.

Everything was going smooth till I got stuck on this query in my old codebase.

INSERT INTO recycletag (id,tagid,isassign) 
VALUES (?,?,?) ON DUPLICATE KEY UPDATE isassign = VALUES(isassign)

It was easy to save the entity using Spring Data JPA but how to replicate this operation using Spring Data JPA?

Ravi
  • 30,829
  • 42
  • 119
  • 173
Dave Ranjan
  • 2,966
  • 24
  • 55
  • *I got stuck* any error ? – Ravi Feb 01 '18 at 17:56
  • As others have said, there is still an option for using almost the actual same `SQL` statement. Since I would assume that your JPA rep is mostly the default code, you can use `@Modifying @Query("update...")` annotations. – M. Prokhorov Feb 01 '18 at 18:25
  • @M.Prokhorov Yes that's always the option, but I want to do it JPA way, don't want to write native query. – Dave Ranjan Feb 01 '18 at 19:38
  • 1
    @DaveRanjan, even Spring documentation itself doesn't hesitate to use JPQL queries. It's really hard to infer anything complex from what annotation programming can provide. As a rule of thumb, I'd say that if your query does anything other than the simplest thing, then it's better to write a query string. (I may be wrong though, let's see if someone has an actual answer). – M. Prokhorov Feb 01 '18 at 19:48
  • I agree with you @M.Prokhorov, but this is a common scenerio for almost all save queries, so I'll have to write native query for saving entities. I was just hoping somebody will have a more generic solution. – Dave Ranjan Feb 01 '18 at 19:51
  • @DaveRanjan, if that's indeed a common, then there may be some games you can play with framework extensions to inspect and modify the jpa-generated querystrings. I'm not familiar with this enough to suggest a more detailed strategy, however. – M. Prokhorov Feb 01 '18 at 20:00
  • Thanks M.Prokhorov :) Sometimes just talking to someone gives you hints. – Dave Ranjan Feb 01 '18 at 20:03

0 Answers0