0

I have a many to many User <-> Roles relation. The User entity looks like this:

@Entity
@Table(name = "user",
        uniqueConstraints = {@UniqueConstraint(columnNames = {"username", "email"})})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
    private Set<Role> roles = new HashSet<>();
}

And the Roles entity is the following:

@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = true, nullable = false)
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(length = 60, name = "roleName", updatable = true, nullable = false)
    private RoleName roleName;
}

Everything works fine, except one thing. When I insert two users with the same role the roles table getting two records with the same role, but different IDs.

enter image description here

The question is, can I eliminate this behavior? Ideally the ROLES table should not contain duplicated roles.

Any advice would be appreciated. :)

user3457182
  • 37
  • 1
  • 7
  • Tell us what exactly is the problem. If 2 users have the same role, then naturally you need 2 records - one record defining that user 1 has this role and another record defining that user 2 has this role. If you have 100 users with this role, there will be 100 records with this role. What exactly is the problem? – mentallurg Dec 15 '19 at 23:04
  • When I added more users with the same role name (Role entity isn't from the database) The Roles table was getting updated, and finally the table contained duplicated roles with different id-s. But az @Johna mentioned, I made a mistake in the business logic. (The role entity should be retrieved from database) – user3457182 Dec 15 '19 at 23:14

1 Answers1

0

I cannot find a problem in your entity mapping. The problem should be in the business logic where you try to save the user entity.

The problem you have described can happen if you set a not-yet-saved Role entity to a User. In other terms, your Role do not have an id field yet.

You need to get the Role from your persistent provider and set it to User.

If you are using spring-data, it can be like:

User user = ....
Role role = rolesRepository.findByName(roleName);
user.setRole(role); 
// The persist User
Johna
  • 1,836
  • 2
  • 18
  • 29
  • @mentallurg. Duplicates is a problem for him. Thats why he has asked how to eliminate it :). He has accepted the answer too. Do you still think I have misunderstood the question. – Johna Dec 15 '19 at 22:55