如何引用已保存在数据库中的实例?

How to refer to an instance already saved in database?

我正在尝试在 spring 中建立电影和演员之间的关系模型。这是我的两个 类:

@Entity
public class Movie {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String genre;
    private String year;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Actor> actors;

// getters and setters
@Entity
public class Actor {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
    private String age;

// getters and setters

我已经定义了一个多对多的单向关系,它工作正常,但在下面的情况下不行。如果我插入一部新电影,其中包含数据库中尚不存在的新演员,效果很好,所有 table 都已正确更新。但是如果我想插入一个已经保存的演员的新电影,我不想保存两次,我希望关系 table 指的是已经保存的演员并且在 Actor table 没有添加新演员。

以下 JSON 是发送到端点以创建新电影的文件:

{
  "actors": [
    {
      "age": "string",
      "dni": "string",
      "name": "string",
      "surname": "string"
    }
  ],
  "genre": "string",
  "title": "string",
  "year": "string"
}

那么我怎样才能插入一个已经在数据库中的演员的电影以便被引用呢?因为如果我插入一个具有完全相同数据的新对象,我会将该参与者保存两次,并且在标识符重复的情况下,我会得到唯一索引或主键违规。

非常感谢您的帮助!

如果两边都有对象标识符[@Id],则可以使用session.saveOrUpdate

来自 Hibernate 文档:

saveOrUpdate() does the following:

  • if the object is already persistent in this session, do nothing
  • if another object associated with the session has the same identifier, throw an exception
  • if the object has no identifier property, save() it
  • if the object's identifier has the value assigned to a newly instantiated object, save() it
  • if the object is versioned by a <version> or <timestamp>, and the version property value is the same value assigned to a newly instantiated object, save() it
  • otherwise update() the object

如果数据库中已有actor,必须先获取,然后添加到列表中。

 @Autowired
 ActorRepository actorRepository;

 Optional<Actor> actorOptional = actorRepository.findById(id);
 if(actorOptional.isPresent()){
     movie.getActors().add(actorOptional.get());
 }else{
   // create new actor and add it to the list
 }