简体   繁体   中英

Spring MVC - Instantiate nested object only when input is filled

I have these models:

@Entity
public class User {
     //...
    @NotBlank private String login;
    @NotBlank private String password;
    @Valid @OneToOne private Person person;
     //...
}

// And

@Entity
public class Person {
     //...  
    @NotBlank private String name;
     //...
}

And this insert method in User controller:

@RequestMapping(method = POST)
public String insert(@Valid User user, BindingResult result){

}

And this form

<p>Login : <input type="text" name="login" /></p>
<p>Pass : <input type="text" name="password" /></p>
<p>Name : <input type="text" name="person.name" /></p>

Association between Person and User is Optional. So don't need to fill person.name input.

But when controller receive User's information @Valid annotation is validating both User and Person objects even person.name is empty.

I realized that Controller is receiving Person object instance always.

Is it possible to receive null in Person when person.name input is not filled?

When I remove person.name input from the form, its OK, I receive null. But peson name is optional and I cant remove from form.

Try to remove @NotBlank at Person Name :

@Entity
public class Person {

    private String name;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM