Reputation: 3814
I am using Spring Boot, Spring Data and JPA Rest Repositories and MySQL as a database and I want to do several things when my entity is created.
Let's say I have a MainChecker entity and each of them has various Checkers that need to be created/deleted or updated whenever MainChecker is created/updated.
This is what I want to do:
Use Spring Data Repositories to insert MainChecker entities from the frontend to my database (so it would be a JSON with parameters).
Each of these MainChecker entities will have boolean fields (among others).
Based on these boolean fields, I want to CRUD other entities accordingly. So, if a MainChecker has some boolean changed to false (redChecker, for example), I would like to delete that redChecker. But the other checkers would still remain (for example green and blue)
Bonus problem! One field is a JSON containing parameters that are to be used for creation of these other entities.
A very simplified example:
@Entity
@Table(name="master_checker", catalog="checkers")
public class MasterChecker() {
private Long id;
private Boolean blueChecker;
private Boolean greenChecker;
private Boolean redChecker;
// constructors
// getters and setters
}
I have some ideas but not sure which one of them is a good way to go.
Should I put a @OneToOne relationship for each field? Then a Boolean won't do, it will have to be objects. And how do I create an object from a boolean value and insert parameters from my JSON field?
Make a custom getter and setter and create the object in the service layer (not liking this option very much)
How to do this (in an elegant and decent way)?
Upvotes: 0
Views: 500
Reputation: 484
One option is to use RepositoryEventHandlers, e.g. @BeforeCreate
and @BeforeSave
.
It will allow you to add some extra logic during creation/update of an object, you can e.g. check if those checkers are true or false and do required CRUD actions in a repository.
See more in the documentation.
Upvotes: 1