首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Version - Spring启动

@Version - Spring启动
EN

Stack Overflow用户
提问于 2018-02-20 10:53:25
回答 1查看 3.7K关注 0票数 1

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

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

代码语言:javascript
复制
@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);
}

在模型上我有这样的想法:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
{
    "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中发送的版本,而是

代码语言:javascript
复制
where id=24 and version=30, is where id=24 and version=31
EN

回答 1

Stack Overflow用户

发布于 2019-10-22 14:28:16

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

vlad在他的博客中经常提到“分离实体”( 这里 )。

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

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

使用类似:

代码语言:javascript
复制
entityManager.detach(entityObject)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48883587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档