Issue
I am facing the problem while binding nested object in Model Attribute. I have one class Book, in which I have nested class Subject as below :
@Entity
@Table(name = "book")
public class Book {
// Other properties...
// With all getter setter..
@ManyToOne
@JoinColumn(name="subject_id",nullable=false)
@NotBlank(message = "Please select subject")
private Subject subject;
// Getter setter of subject;
}
Also I have implemented Formatter class for Subject as below :
@Component
public class SubjectFormatter implements Formatter<Subject>{
@Autowired
SubjectService subjectService;
@Override
public String print(Subject object, Locale locale) {
return object.getName();
}
@Override
public Subject parse(String id, Locale locale) throws ParseException {
return subjectService.getSubject(id);
}
}
And added the formatter in spring configuration :
@EnableWebMvc
@Configuration
@PropertySource(value = { "classpath:application.properties" })
@ComponentScan(basePackages = "com.vbera.main")
@EnableJpaRepositories(basePackages = "com.vbera.main")
public class SpringConfiguration extends WebMvcConfigurerAdapter {
//Other bean definitions...
@Bean(name="conversionService")
public FormattingConversionService conversionService() {
FormattingConversionServiceFactoryBean bean = new FormattingConversionServiceFactoryBean();
bean.setRegisterDefaultFormatters(false);
bean.setFormatters(getFormatters());
return bean.getObject();
}
private Set<Formatter> getFormatters() {
Set<Formatter> converters = new HashSet<Formatter>();
converters.add(new SubjectFormatter());
return converters;
}
}
Still I'm getting below exception on submit :
Failed to convert property value of type java.lang.String to required type com.vbera.main.pojo.Subject for property subject
JSP view for Subject list rendering :
<form:label path="subject" for="subject">Subject</form:label>
<form:select path="subject" class="form-control input-md">
<form:option value="">--- Select ---</form:option>
<form:options items="${subjectList}" itemLabel="name"
itemValue="id" />
</form:select>
Solution
I find out the solution from Spring 3.1 Form and List Binding, Java - SpringMVC - Get parameter in the controller link.
In one answer, it is suggested to have below jsp select tag :
<form:select path="subject.id" class="form-control input-md">
<form:option value="">--- Select ---</form:option>
<form:options items="${subjectList}" itemLabel="name"
itemValue="id" />
</form:select>
Answered By - Vimal Bera