简体   繁体   中英

In OOP, should I define different objects for writing to and reading from a table?

How should I return the Primary Key of my table-read API requests without requiring a Primary Key on my table-write API requests? They use the same object.

I have a Person class and two controller functions.

public class Person {
    private Integer id; // this is the primary key in my table
    private String name;
    private Integer houseId;
    private Integer age;
}
@RestController
public class TestController {
    @RequestMapping("/")
    public List<Person> fetchAll() { // this function does a "SELECT *" on all rows
        return personDao.findAll();
    }

    @PostMapping(value = "/createPerson")
    public void createPerson(@RequestBody Person person) { // this function does an "INSERT"
        personDao.insertPerson(person);
    }
}

I don't want to require the table Primary Key (class attribute "id") on all my "createPerson" API requests, since the client won't know it. I want to skip on that value, and let the table increment the PK on insert.

However, I want to return the "id" in the "fetchAll" API requests. And I want it defined on the Person object.

I don't see a way to do this besides making "id" Optional type, or defining two separate objects: "PersonRequest" and "PersonResponse", both which will extend "Person" class. Both of which seems like a bad practice

Is there something I'm missing?

Since you said that you want to have the id automatically incremented make sure to add the annotations below to your id field:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

There is nothing stopping you from saving an object without an id even though it has a property id. If you do:

Person person = new Person(); //person is empty here
person = personRepository.save(person);

The return value assigned to person will have an id. Also when you execute:

Person person = personRepository.findById(id);

The person object will have the id, I am not sure what else is confusing you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM