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?