我一直试图让@Version工作,但我似乎做不到,我正在构建一个Rest ,当我试图编辑时,我想确保用户正在编辑的版本是当前版本,而不是由其他人打开和编辑的版本,因为我使用了
这是当前我的控制器代码:
@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);
}在模型上我有这样的想法:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String slug;
@Lob
private String lyrics;
@CreationTimestamp
private Date createdAt;
private Date updatedAt = new Date();
private Date deletedAt;
@OrderBy("id")
@ManyToMany
@JoinTable(joinColumns = @JoinColumn(name = "song_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "types_id", referencedColumnName = "id"))
private List<SongType> types;
@JsonProperty(access = Access.READ_ONLY)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property = "name")
@JsonIdentityReference(alwaysAsId=true)
@ManyToOne
private User user;
@javax.persistence.Version
private int version;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
... other getters and setters ...这是我用来更新歌曲的json:
{
"id": 24
"name": "New song for Update test",
"slug": "new-song-for-update-test",
"lyrics": "lyrics for the song update",
"types": [
{
"id": 2
}
],
"version": 30
}我使用.properties文件来显示sql绑定,而更新正在执行的版本不是在json中发送的版本,而是
where id=24 and version=30, is where id=24 and version=31发布于 2019-10-22 14:28:16
我们在项目中也遇到过类似的情况,我们发现@Version验证只适用于detatch对象。至少使用Hibernate,就像我们的情况一样。
vlad在他的博客中经常提到“分离实体”( 这里 )。
从数据库获取的currentSong实体被附加到上下文中。
我建议您克隆或映射您的currenSong到一个副本,并保存这个分离的副本。或者在保存之前将其与上下文分离。(我们做了最后一次)。
使用类似:
entityManager.detach(entityObject)https://stackoverflow.com/questions/48883587
复制相似问题