0
votes

I have 3 tables, User, Role, and User_role. User has a OneToMany relationship mapped by "user" with a CascadeType.Merge and user_role has 2 ManyToOne Relationships with cascadeTypes.All however the user_table never populates with data when running hibernate. Instead values are only populated in the user and role tables, but never the user_role table.

User Table Definition

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

private String username;
private String password;
private String firstName;
private String lastName;

private String email;
private String phone;
private boolean enabled = true;

@OneToMany(mappedBy = "user", cascade=CascadeType.MERGE, fetch = 
FetchType.EAGER)
@JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();

UserRole Table:

@Entity
@Table(name="user_role")
public class UserRole implements Serializable {
private static final long serialVersionUID = 890345L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long userRoleId;

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL, 
optional=false)
@JoinColumn(name = "user_id")
private User user;

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL,  
optional=false)
@JoinColumn(name = "role_id")
private Role role;

public UserRole () {}

public UserRole (User user, Role role) {
    this.user = user;
    this.role = role;
}

public long getUserRoleId() {
    return userRoleId;
}

public void setUserRoleId(long userRoleId) {
    this.userRoleId = userRoleId;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

}

Call To userRepository.save() in userServiceImpl that is called from a commandLine Runner.

@Service

public class UserServiceImpl implements UserService {

private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);


@Autowired
private UserRepository userRepository;

@Autowired
private RoleRepository roleRepository;


// Indicates a  Database Transaction
@Transactional
public User createUser(User user, Set<UserRole> userRoles) {
    User localUser = userRepository.findByUsername(user.getUsername());

    if(localUser != null) {
        LOG.info("User with username {} already exist. Nothing will be done. ", user.getUsername());
    } else {


        for (UserRole ur : userRoles) {
            roleRepository.save(ur.getRole());
        }

        Set<UserRole> currentRoles =user.getUserRoles();

        currentRoles.addAll(userRoles);
        user.setUserRoles(currentRoles);


        localUser = userRepository.save(user);
    }

    return localUser;    
}

}

Main Class Run()

    public void run(String... args) throws Exception {
    User user1 = new User();
    user1.setFirstName("John");
    user1.setLastName("Adams");
    user1.setUsername("j");
    user1.setPassword(SecurityUtility.passwordEncoder().encode("p"));
    user1.setEmail("[email protected]");
    Set<UserRole> userRoles = new HashSet<>();
    Role role1 = new Role();
    role1.setRoleId(1);
    role1.setName("ROLE_USER");
    userRoles.add(new UserRole(user1, role1));

    userService.createUser(user1, userRoles);
}
2
Do we really need 3 user_role table?Supun Dharmarathne
Yes the user_role table is an associative table which addresses the ManyToMany relationship User and Roles share.Matt

2 Answers

0
votes

CascadeType.MERGE will only cascade merge events. Persist events wont cascade so if you try to save a new user, the persist event will not cascade to User_role and no entries will be inserted into the user_role table.

Try to add the CascadeType.PERSIST or change to CascadeType.ALL in order to cascade save the record in the database.

@OneToMany(mappedBy = "user", cascade={CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.EAGER)

You can find out more about Cascade events in this answer: What do REFRESH and MERGE mean in terms of databases?

0
votes

I was able to persist the data to the user_role associative table by implementing the JPA entity manager. A new EntityManager class was instantiated and the data was persisted through the javax.persistence .merge() method.