Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
@版本-Spring启动_Spring_Spring Boot_Spring Rest - Fatal编程技术网

@版本-Spring启动

@版本-Spring启动,spring,spring-boot,spring-rest,Spring,Spring Boot,Spring Rest,我一直试图让@Version正常工作,但我似乎做不到,我正在构建一个Rest API,当我尝试编辑时,我想确保用户正在编辑的版本是当前版本,而不是其他人打开和编辑的版本,为此,我使用了@javax.persistence.Version 这是当前我的控制器代码: @InitBinder("song") protected void initBinder(WebDataBinder binder) { binder.setValidator(new SongValidator()); }

我一直试图让
@Version
正常工作,但我似乎做不到,我正在构建一个Rest API,当我尝试编辑时,我想确保用户正在编辑的版本是当前版本,而不是其他人打开和编辑的版本,为此,我使用了
@javax.persistence.Version

这是当前我的控制器代码:

@InitBinder("song")
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new SongValidator());
}

@PutMapping("{song}")
public ResponseEntity<?> update(@PathVariable("song") int songId, @Valid @RequestBody Song song) {
    Song currentSong = songService.findSongByIdAndDeletedAtIsNull(songId);
    if (currentSong == null) {
        return new ResponseEntity(new CustomErrorType(
                "Song with id " + songId + " not found."
        ), HttpStatus.NOT_FOUND);
    }

    currentSong.setName(song.getName());
    currentSong.setLyrics(song.getLyrics());
    currentSong.setTypes(song.getTypes());

    songService.save(currentSong);
    return new ResponseEntity<Song>(currentSong, HttpStatus.OK);
}
我使用
.properties
文件来显示
sql
绑定,并且更新所执行的版本不是在
json
中发送的版本,而是

where id=24 and version=30, is where id=24 and version=31

我们在项目中也遇到了类似的情况,我们发现@Version验证只对detatch对象有效。至少使用Hibernate,就像我们的例子一样

弗拉德·米哈尔恰(vlad mihalcea)在他的博客中实际上总是提到“分离的实体”

从数据库获取的currentSong实体已附加到上下文

我建议您克隆或将您的currenson映射到一个副本,并保存此分离副本。 或者在保存之前将其与上下文分离。(我们已经做了最后一个)

使用like:

entityManager.detach(entityObject)

在JSON中传递版本,但不使用它做任何事情。您需要在要更新的实体上设置它,或者自己进行手动检查。我已经试过
currentSong.setVersion(song.getVersion())
,但它仍然没有做任何事情,我已经进行了手动检查以进行测试,但我认为jpa会自动完成。我发现如果您使用的是Spring Boot Devtools,在某个地方进行修改并允许应用程序自动重新启动,每当发生冲突时,OptimisticLockException将开始抛出。我无法理解为什么它会以这种方式开始工作。
where id=24 and version=30, is where id=24 and version=31
entityManager.detach(entityObject)