Search code examples
javaspringspring-bootspring-mvcmybatis

Is it acceptable to perform an update operation within a @GetMapping method in Spring MVC?


// Read received message
@GetMapping(value = "msgReadReceived")
public String readReceivedMessage(@RequestParam("msg_no") Long msgNo, Model model) {
    // Retrieve the message using msgNo
    Message receivedMessage = msgService.getReceivedMessageById(msgNo);

    // If the read date is 'null', perform an update
    if (receivedMessage.getMsg_readdate() == null) {
        // Update msg_readdate when the message is clicked
        msgService.updateReadDate(msgNo);
        // Retrieve the message again after the update
        receivedMessage = msgService.getReceivedMessageById(msgNo);
    }

    model.addAttribute("receivedMessage", receivedMessage);

    // Redirect to the message reading page
    return "kdw/msgReadReceived";
}

I have a Spring MVC method annotated with @GetMapping, in which I retrieve and display a received message. If the read date is null, I update it when the message is clicked, and then retrieve the message again after the update. I'm curious whether it is considered acceptable to perform an update operation within a @GetMapping method in Spring MVC. If this practice is discouraged, I attempted to separate the logic, but currently facing challenges due to my limited knowledge. I would greatly appreciate guidance on best practices for handling such scenarios in Spring MVC. If this approach is not recommended, any assistance in achieving proper separation would be invaluable.


Solution

  • If you want to update information in the DB, you should separate concerns a little. GET requests should not update information in the DB.

    For your usecase, you should be allright but it's generally good to keep logic outside of controllers. They should just obtain / update information, but the logic should be inside the service methods.

    What James said in his answer, that's a good idea too, to make front-end call two endpoints, but that would cost you more. His answer is from ChatGPT and might not be the best.