ar.thewaterfall
ar.thewaterfall

Reputation: 835

Two models in the form Spring MVC

Suppose, I have a user model:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

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

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

@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="user_profile_id")
private UserProfile profile;

UserProfile model:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

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

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

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

I can add this model in the controller:

@RequestMapping(value = {"/user/{id}"}, method = RequestMethod.GET)
public String showUser(ModelMap model, @PathVariable int id) {
    User user = userService.findById(id);
    model.addAttribute("user", user);

    return "UserView";
}

Then It's possible to access the model in the .jsp page like that:

<form:form method="POST" modelAttribute="user">
    <form:input type="text" path="username"/>
    <form:input type="password" path="password"/>
</form> 

But the question is - how can I edit UserProfile model which is located in the User model at the same time while I'm editing User model which is passed from controller to .jsp page?

The question is not duplicate because I wanted to know if "path" can handle hierarchal attributes but not how just to pass one object to view.

Upvotes: 0

Views: 937

Answers (1)

Gnk
Gnk

Reputation: 720

Use like this

<form:input type="text" path="profile.email"/>

And I do not recomend you to pass your entity to front, instead use DTOs for decoupling

Upvotes: 2

Related Questions