简体   繁体   中英

Java Spring CRUD repository method “deleteById” doesn't work

I just stacked into a problem with my web Spring application. I added a method deleteById which declared in MessageRepo which extended from CRUDRepository. This method works perfect and it redirect to my "main" page, but there are nothing change in my MySQL DB. Hope that anybody can answer me what's wrong with my app. Feel free to answer. Look down below for this method in my controller

    @PostMapping("/main/{id}")
    public String delete(@PathVariable(value = "id") Long id) {

        messageRepo.deleteById(id);

        return "redirect:/main";
    }

That's my how my messages look like in view with button for delete anything.

                        <#list messages as message>
                        <div class="task-card">
                            <p class="task-card-p">${message.text}</p>
                            <form method="post" action="/main/${message.id}">
                                <input type="hidden" name="_csrf" value="${_csrf.token}"/>
                                <button type="submit" class="task-card-btn">delete</button>
                            </form>
                        </div>
                        </#list>

That's my messageRepo. There no any methods cause of i extended of crudRepo.

public interface MessageRepo extends CRUDRepository<Message, Long> {

}

You have to add @Transactional annotation on your controller's delete method. You have to import org.springframework.transaction.annotation.Transactional to use this annotation. Also make sure you add getters and setters in your Message class. This solution will do the work for you but as a good practice you should add a service layer between your Controller and Repo Class. Mark all the methods of Service class that do Database operations as @Transactional .

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