Search code examples
springspring-mvcspring-securityspring-roo

Spring roo and One-To-Many relationship in GUI generation


I cannot generate an appropriate GUI via roo for a one-to-many relationship. In particular, I would need a multiple choice element to select among the authorities (spring security) to associate to the user.

I created my RegisteredUser class:

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class RegisteredUser extends MyUser implements UserDetails,
    CredentialsContainer {

private String password;
private String username;
private Boolean enabled = true;
private Boolean accountNonExpired = true;
private Boolean credentialsNonExpired = true;
private Boolean accountNonLocked = true;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<MyBaseAuthority> authorities = new HashSet<MyBaseAuthority>();

@Override
public void eraseCredentials() {
    password = null;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
}

@Override
public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return username;
}

@Override
public boolean isAccountNonExpired() {
    return accountNonExpired;
}

@Override
public boolean isAccountNonLocked() {
    return accountNonLocked;
}

@Override
public boolean isCredentialsNonExpired() {
    return credentialsNonExpired;
}

@Override
public boolean isEnabled() {
    return enabled;
}
}

Then MyBaseAuthority class:

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class MyBaseAuthority extends ObjectWithId implements
    GrantedAuthority {
   private String authority;

@Override
public String getAuthority() {
    return authority;
}
}

Then I had to manually create the controller for MyBaseAuthority, but not for RegisteredUser (generated by webmvc command):

@RequestMapping("/registeredusers")
@Controller
@RooWebScaffold(path = "registeredusers", formBackingObject = RegisteredUser.class)
public class RegisteredUserController {
}

@RequestMapping("/authorities")
@Controller
@RooWebScaffold(path = "authorities", formBackingObject = MyBaseAuthority.class)
public class MyBaseAuthorityController {
}

On the GUI, I can create and list all authorities and registered users. However, when creating a registered user, I can only set string fields and boolean fields, but not the one-to-many relationship. How can I fix that?


Solution

  • If I were trying to acomplish this task I would print out all of my checkboxes with the available options as array keys with a name like so:

    <input type="checkbox" name="role[]" value="ROLE_ONE">
    <input type="checkbox" name="role[]" value="ROLE_TWO">
    

    Then, I would map these parameters to a String[] array like in this post

    @RequestParam(value="myParam[]" String roles)
    

    I would then loop over the strings and add create the MyBaseAuthority objects, attach your user and persist() them.