Select Java Object from Spring Form drop down menu

706 views Asked by At

Is it possible to select whole Java Object from Spring Form's drop down menu? I used LinkedHashMap, but it doesn't work.


I have relation Many To One between table Agent and table Roles (every Agent has one role eg. user, admin). I use hibernate so I have to operate on Object, not Id's from database. My problem is that I want to create drop down menu with list of all roles from my database and when I pick one element, this Object goes to my Agent Object and save in my database.

I have List with my Roles Objects

List<Roles> rolesList = rolesService.getAllRoles();

Which comes from this:

public List<Roles> getAllRoles() {
    return session().createQuery("from Roles").list();
}

and I tried something like this:

In my AgentController:

@RequestMapping("/createagent")
public String createAgent(Model model) {
    Agent agent = new Agent();
    List<Roles> rolesList = rolesService.getAllRoles();
    Map<Roles, String> rolesMap = new LinkedHashMap<Roles,String>();
    for (int i=0; i<rolesList.size(); i++){
        rolesMap.put(rolesList.get(i), rolesList.get(i).getRole());
    }
    model.addAttribute("rolesMap", rolesMap);
    model.addAttribute("agent", agent);
    return "createagent";
}

In my jsp file:

<tr><td>Roles:</td><td>
<sf:select path="roles" multiple="false">
<sf:options items="${rolesMap}"></sf:options>
</sf:select>
</td></tr> 

My Roles Object:

@Entity
@Table(name = "roles")
public class Roles {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "roles_seq_gen")
@SequenceGenerator(name = "roles_seq_gen", sequenceName = "roles_id_seq")
@Column(name = "id")
private long id;

@Column(name = "role")
private String role;

It shows excactly what I want but when I click position in my drop down menu and submit it, my form don't save my Object properly. It nested it ... I don't know how to subscribe this, maybe my toString() function output clear little bit.

Agent [id=0, username=TestUsername, password=TestPassword, roles=Roles[id=0, roles=Roles[id=0, roles=user]] ...

My Agent Object:

 @Entity
 @Table(name="agent")
 public class Agent {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="agent_seq_gen")
    @SequenceGenerator(name="agent_seq_gen", sequenceName="agent_id_seq")
    @Column(name="id")
    private long id;

    @Column(name="username")
    private String username;

    @Column(name="password")
    private String password;

    @ManyToOne
    @JoinColumn(name="roles_id")
    private Roles roles;

My jUnit test runs fine, it's something wrong with my Spring Form or with my controllers... I don't know.

1

There are 1 answers

5
AudioBubble On

I would suggest to use ModelAttribute and reference the form object to the said properties, like, agent.getRoles().

createAgent(@ModelAttribute("agent") Agent agent) should work in what you're trying to accomplish.