This is my entity:
@Entity
@Table
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class Sample {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private boolean whatever;
}
And I want to insert mock data to the db:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApplication.class, args);
Service service = context.getBean(Service.class);
service.save(new Sample("name", true); //Doesnt compile, lacks id
service.save(new Sample(10, "name", true); //If row with id 10 exists, it gets updated
}
}
As explained in the comments, either it doesn't compile or it replaces the row.
When adding data through the controller, I can just leave the id on the json undefined and it will generate a new one. How does the controller achieve this?
EDIT: The service saves the object by calling the save method of the JpaRepository
public Sample save(Sample s) {
return repository.save(s);
}