If you have plenty of tables in your database, which I presume you do since you're asking the question, I'd suggest you put all of the CRUD logic into separate classes called Repositories (e.g. ModelRepository).
These classes should have all the things necessary and they'd best be implemented via the interface that has the C R U and D methods, so that if the implementation needs to undergo some changes, everything keeps on working because of the usage of interface. So for every model you need 2 classes, ModelRepositoryInterface
which can even extend a common interface with these 4 operations and each can have some additional methods specific to the class itself; and the class that implements the interface, say ModelRepositoryImplementation
.
Some basic example, let's assume your Model is called Course
:
public class Course {
//your class logic, constructor, getters, setters, etc.
}
This would be it's repository interface:
public interface CourseRepositoryInterface {
void addCourse(Course course);
void deleteCourse(Course course);
void updateCourse(Course course);
List<Course> getAllCourses();
}
Something like that, of course it can have more/less methods varying from your needs.
Finally you need a class that implements that interface like:
public class CourseRepoWithMySqlDatabase implements CourseRepositoryInterface {
void addCourse(Course course) { //TODO: Implement it }
void deleteCourse(Course course) { //TODO: Implement it }
void updateCourse(Course course) { //TODO: Implement it }
List<Course> getAllCourses() { //TODO: Implement it }
}
In this class you would implement the methods to do what they need to do with, for example, MySql database. In case you ever needed to switch from MySql to, let's say, another type of database or a no database implementation, you'd just use another class to implement the interface, and pass that where the interface parameter is required.
Pay attention: this is very important. You always need to require the interface in the place where you plan to use its methods.