0

Spring data jpa + postgres.

Have an entity

class Entity {

@Id
@GeneratedValue// generator from here https://stackoverflow.com/questions/60989691/how-to-manually-set-a-value-for-generatedvalue/61007375#61007375
private int id;

private String value;

}

And what I wish to do is to UPDATE an existing entity, setting a different id (be it a bad practice or not) value.

By default it of course is treated as a new entity and is attempted to be INSERTed.

Going by the flow of @Modifying seems to do the job right, but currently struggling to find if I can pass the whole entity instead of pinpointing every field:

update Entity e set e.id=?1, e.value=?2 where... to update Entity e set e=?1

So the questions here would be: 1. Is there a way to gracefully do an "UPDATE" with modified id in terms or regular spring-data-jpa flow? 2. If not, is there a way to provide the full entity to be consumed by the @Query?

Draaksward
  • 759
  • 7
  • 32

1 Answers1

0
  1. Is there a way to gracefully do an "UPDATE" with modified id in terms or regular spring-data-jpa flow?

If you are using GenerationType.AUTO strategy for @GeneratedValue (AUTO is the default strategy), then you can set id of Entity to null before calling save. It will insert a new record with rest of the fields being the same as original. id of new record will be generated automatically by database engine.

If you are using GenerationType.AUTO strategy for @GeneratedValue

  1. If not, is there a way to provide the full entity to be consumed by the @Query?

You can chose not use @Query. A far simpler approach can be using default save method provided by JPA repositories to directly pass an Entity object.

narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58
  • My answer assumes that you are using `AUTO` strategy (which is default if none is provided). But, the same approach can be used for other id generation strategies as well. – narendra-choudhary Apr 03 '20 at 11:52
  • Sorry, but my case is "I want to manually define the ID"(and no, `@GeneratedValue` should remain) and have query be resolved to UPDATE. – Draaksward Apr 03 '20 at 11:57