简体   繁体   中英

How can i save related entity in Database using dual Many-To-Many relationship?

I have two entities:

User
Work

they have many-to-many relationship with each-over.

  @ManyToMany(
      fetch = FetchType.LAZY,
      cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
  @JoinTable(
      name = "user_work",
      joinColumns = @JoinColumn(name = "work_id"),
      inverseJoinColumns = @JoinColumn(name = "user_id"))
  private List<User> workUsers;

when i add new work using JPA:

List<UserDto> users = new ArrayList<>();
users.add(new User(something something));

WorkDto work1 = new WorkDto(1, users));

workRepository.save(workMapper.fromDto(work1));

problem: when i save my work entity in the database it does not save user, so when i extract it, work says that is has no users.

How can i insert work into database and add users to it as well? I have mutual table with work_id and user_id of course

Are you executing it within a transaction with @Transactional ? Have you @Override the equals method ?

More detail is needed like the relationship in the User class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM