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);
}
Your problem os that your pojo Sample do not have a constructor without id. You've used the annotations @NoArgsConstructor and @AllArgsConstructor that gives you an empty constructor and a constructor with all the fields, respectvly. In the controller It works due to the serialization and deserialization present on the controller (Jackson by default on Spring) that is capable of building the object with missing fields, using the empty constructor and direct access to fields.
All you have to do is to create an constructor with the fields you need on your pojo Sample, so in the case described would be something like:
public Sample(String name, boolean whatever) {
this.name = name;
this.whatever = whatever;
}
This will fit your problem.