I want the aggregate root element to control whether to do an update or an insert. Please tell me how to implement this in the isNew method.
@Data
public class State implements Persistable<String> {
@Id
private String id;
private String name;
public State(String id, String name){
this.id=id;
this.name=name;
}
@Override
public boolean isNew() {
return true;
}
}
@SpringBootApplication
public class Isnew2Application {
public static void main(String[] args) {
SpringApplication.run(Isnew2Application.class, args);
}
@Bean
CommandLineRunner runner(StateRepo stateRepo){
return args -> {
stateRepo.save(new State("ID","Idaho"));
stateRepo.save(new State("IA","Iowa"));
stateRepo.save(new State("AL","Alabama"));
stateRepo.save(new State("AK","Alaska"));
};
}
}
When you run the code again, an exception is naturally thrown.
One way or another you need to change the
isNew
state of the entity. You can do it explicitly in your code, you cand do it in a life cycle callback, you can decide it based on the constructor use. See https://spring.io/blog/2021/09/09/spring-data-jdbc-how-to-use-custom-id-generation/ for various options and how to implement them.