October 22, 2024
Chicago 12, Melborne City, USA
java

ManyToMany:: How to save data only in the “joining table” and save only “owning side”


There is a Many-to-Many relationship between the "MyUser" and "Roles" tables, with "joining table" = "USERS_ROLES".
When I save "MyUser":: the data is successfully saved to the "MyUser" table, to the "Roles" table and to the "joining table" table.
I do it like this::

@Entity
@Table(name = "users")
public class MyUser {
 ...

  @ManyToMany(cascade = {CascadeType.PERSIST})
  @JoinTable(name = "USERS_ROLES",
      joinColumns = {@JoinColumn(name = "user_id_pk")},
      inverseJoinColumns = {@JoinColumn(name = "role_id_pk")})
  private List<Roles> listRoles;
 ...
}

And that’s it::

@Entity
@Table(name = "roles")
public class Roles {
  ...
  @ManyToMany(mappedBy="listRoles")
  private List<MyUser> myUsersList;
  ...
}

I want the data to be saved only to the "MyUser" table and to the "joining table", i.e. so that the data is not saved to the "Roles" table.

If I use "CascadeType.REMOVE", an error is thrown. Here it is:: "TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing: Roles".

Well, that is, the "MyUser" object contains another "Roles" object, I save "MyUser", and I do not save "Roles", so this error is thrown.

Question: so how do I save the data only to the "MyUser" table and to the "joining table" table, i.e. so that the data is not saved to the "Roles" table ?
Does anyone have any ideas?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video