R
R
Rick2017-12-11 12:15:10
Java
Rick, 2017-12-11 12:15:10

How to prevent simultaneous access to a database file/cell?

Greetings!
There is a controller method:

@Controller
public class NoteController {

    @Autowired
    private NoteService noteService;

    @Autowired
    private UserService userService;

    private NoteFileWriter noteFileWriter = new NoteFileWriter();

    @RequestMapping(value = "admin/editnote/{id}", method = RequestMethod.POST)
    public String editNotePost(@PathVariable("id")Long id,
                           @ModelAttribute("note")String text){
        //получаем из БД заметку по ID
        Note note = noteService.getById(id);
        //меняем у заметки поле на новое
        note.setText(text);
        //обновляем заметку в БД. 
        noteService.saveNote(note);
        //обновляем заметку в файле
        noteFileWriter.writeNoteToFileWithFOS(note.getId().toString(), text);

        return "redirect:/admin/notelist";
    }
}

and view page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Add Notee</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script	src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container">
    <div class="row">
        <form autocomplete="off" action="#" th:action="@{/admin/editnote/{id}(id=${id})}"
              th:object="${note}" method="post" class="form-horizontal"
              role="form">
            <div style="margin-top: auto">
                <h2>Write your changes</h2>
            </div>
            <div>
                <textarea class="form-control" rows="12"
                          style="margin-top: 10px;" placeholder="Note"
                          name="note" th:inline="text" th:text="${note.text}">
                </textarea>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-block">Save changes</button>
            </div>
        </form>
    </div>
</div>
<br>
<div>
    <form th:action="@{/admin/home}" method="get">
        <button class="btn btn-md btn-warning btn-block" type="Submit">Home page</button>
    </form>
</div>
</body>
</html>

What is the best way to organize simultaneous access to a database file/cell using multithreading?
For example, so that if one user starts editing a note. That the second one could only view the latest version, but could not also transgress to editing?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question