0

I am trying to save two entity objects in a database, with the same id. It allows me for both the requests. I expected to get a response from the controller with 409.

@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Fruit{
    @Id
    @Column(columnDefinition = "UUID")
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "id", strategy = "uuid2")
    private UUID id;
    private String name;
}

I am using PostgreSQL 14 as database and have set unique id on the entity.

Here is my controller.

@PostMapping("/fruit")
public  ResponseEntity<Fruit> addFruit(@RequestBody Fruit newFruit){
    return new ResponseEntity<>(fruitRepository.save(newFruit),HttpStatus.CREATED);
}

Here is my repository.

@Repository
public interface FruitRepository extends CrudRepository<Fruit, UUID> {
}

Here is a integration test. Surprisingly, it allows me to save two users in the database.

@Test
void adding_an_existing_fruit_should_give_409() throws Exception {
    UUID uuid=UUID.randomUUID();
    Fruit mango = new Fruit(uuid, "Mango");
    mockMvc.perform(post("/fruit").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(mango)))
            .andExpect(status().isCreated());

    mockMvc.perform(post("/fruit").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(mango)))
            .andExpect(status().isConflict());
}

Hence, my question. What should be the response for existing entity in database as it is allowing to save duplicate id with unique id?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
Prabhakar Maity
  • 405
  • 3
  • 16
  • 1
    `Save` in JPA is a `Create` or `Update` operation. So the second call just updates the existing entity. Anyway `Save` would raise an exception on an error and would not return the status code for you. This has to be build by yourself. – Andreas Mar 04 '22 at 23:13

0 Answers0