Upsert query using Spring JPA for MS-SQL

Viewed 111

Trying to achieve upsert(insert incase entry doesn't exist else get Id) Id returned from the query1 should be updated as foreign key in another table. Is there a way to achieve it using spring JPA annotations without writing native query or if-else logic in java as below.

   public void saveTagLogEntry(TagLocationDataPacket tagLocationDataPacket){
       Long tagid, zoneid;
       // Get the Zone if exists else add
       Zone zone =  zoneRepository.findZonesByName(tagLocationDataPacket.getZoneName());
       if (zone == null)
           zoneid = zoneRepository.save(new Zone(tagLocationDataPacket.getZoneName())).getId();
       else
           zoneid = zone.getId();
       Tag tag = tagRepository.findTagByExternalId(tagLocationDataPacket.getTagId());
       if (tag == null)
           tagid = tagRepository.save(new Tag(tagLocationDataPacket.getTagId())).getId();
       else
           tagid = tag.getId();
       tagLogentryRepository.save(new TagLogEntry( zoneid, tagid));
   }```
0 Answers
Related