javaweb-applications

Separate object for REST layer and repository layer


I am using springboot + mybatis. I am writing an endpoint StudentController.saveStudent(Student) which takes a Student object and saves it to the database if it is a new student or updates the student row if it is an existing student. There is a mapper xml called SutudentMapper.xml which has the insert query.

<insert id="saveStudent" type="com.example.domain.Student">
insert into student (id, fname, lname, mname, address, contact1, contact2, email) values (#{student.id}, #{student.fname}, #{student.lname}, #{student.mname}, ....)
</insert>

The repository layer (StudentMapper.java) is called via Service layer (StudentService) and the student object is saved in the db.

My service layer, first queries the db to find the student. The repository layer returns Student object. Then I use jackson to serialize the payload and the object returned from db to strings and compare the strings if any changes have been made. If yes then I update the record or I simply return. If the repository returns null, I will save the new student.

But a senior developer says to use different entity class called StudentResource to receive the request body(StudentController.saveStudent(StudentResource) and then convert the StudentResource to Student object and continue to save/update the student object to database.

I feel this is redundant I do not understand why there should be a separate entity class representing the domain class. Can anyone please explain the advantage?

Is this a standard approach like some design pattern or is it opinion based? Can anyone please shed some light on this?


Solution

  • I don't know if what you're saying is what I understand.

    But a senior developer says to use different entity class called StudentResource to receive the request body(StudentController.saveStudent(StudentResource) and then convert the StudentResource to Student object and continue to save/update the student object to database.

    What I understand is: when the front-end calls the API to pass parameters to the back-end, this senior lets you use a StudentResource to receive the parameters?

    If that's the case, I think his original intent was:

    1,Directly using an Entity class (Student) to receive front-end parameters may result in unnecessary data modifications;

    2,The data format of the front-end may not always be exactly the same as the database table structure. Through StudentResource, the back-end is free to adjust the data format without affecting the database table structure, thus reducing coupling and increasing flexibility;

    3,As well as considering that the business logic may use parameters that are not in Student, if they are received by StudentResource, then only new fields need to be added to StudentResource without affecting the database entity class (Student), which reduces the scope of code changes;