【问题标题】:Entity update in EntityManagerEntityManager 中的实体更新
【发布时间】:2017-11-25 15:45:23
【问题描述】:

简要描述整个情况。我有一个实体

public class MovieEntity {
... 
    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<MovieOtherTitle> otherTitles;
...
}

我使用 JPA Spring Data 存储库将电影保存在数据库中

this.movieRepository.save(movie);

然后我给电影添加另一个标题

final MovieOtherTitle movieOtherTitle = new MovieOtherTitle(otherTitle.getTitle(), otherTitle.getCountry());
movieOtherTitle.setMovie(movie);
movieOtherTitle.setUser(user);
this.entityManager.persist(element);

当我想显示这部电影的标题列表时,列表是空白的

movie.getOtherTitles()

重新编译应用程序后,一切正常。为什么?看起来这个实体没有实时刷新列表。我必须再次编译应用程序,然后您才能看到列表中的元素。

【问题讨论】:

  • 你能显示MovieOtherTitle吗?此外,当您创建新标题时,是否正确填充了标题表中的连接列?
  • pastebin.com/u8FquKY8 是的。列中的所有字段均已正确填写。

标签: spring hibernate jpa spring-boot entitymanager


【解决方案1】:
this.movieRepository.save(movie);
final MovieOtherTitle movieOtherTitle = new MovieOtherTitle(otherTitle.getTitle(), otherTitle.getCountry());
movieOtherTitle.setMovie(movie);
movieOtherTitle.setUser(user);

movie.getOtherTitles().add(movieOtherTitles);

this.movieReoository.save(movie);

所以在调用之后 电影.getOtherTitles(); 列表不会为空

可以获取otherTitle的id

movie.getOtherTitles().get(0).getId 

【讨论】:

  • 我立即需要这个已保存对象的 ID。对象movieOtherTitles添加到列表时会有吗?
  • 既然你有 Cascade.All,那么对 movie.save 方法的任何调用也将保存新的 movieOtherTitles 实例。我问你问题了吗?!
  • pastebin.com/AFDyhf5S 这样我就不会得到一个ID,我需要立即添加到列表中。
  • movie.getOtherTitles().get(0).getId
  • 你检查了吗?
猜你喜欢
  • 2012-03-31
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多