在提交弹簧mvc上绑定子对象
我是Java的新手,所以这个问题看起来很简单。 我有一个模型:
@Entity(name="website") public class Website { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="websiteId", nullable=false, unique=true) private long websiteId; @ManyToOne @JoinColumn(name = "publisherId") private Publisher publisher; public Website() { } //... all getter and setter.... }
你看,在网站类中,我有一个Publisher类型的对象:
@Entity(name="publisher") public class Publisher { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="publisherId", nullable=false, unique=true) private long publisherId; private String publisherName; @OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name="publisherId") private List listWebsite; public Publisher() { } //...all getter and setter... }
好的,现在我有一个表单来提交网站类型的整个对象。 我刚创建了一个下拉列表,让用户选择发布者:表单:
--%>
你看,我设置了表单的路径:select tag为“publisher”,itemValue设置为“publisherId”。 发布时,它会将publisherId(长类型值)发布到已发布对象的发布者属性。 validation将失败,因为它需要Publisher类型,而不是长类型。
我的问题:我如何以正确的方式发布Website.Publisher.publisherId?
更新:
我在控制器中添加动作:
@RequestMapping(value = "/add", method = RequestMethod.GET) public String showForm(ModelMap mm, @ModelAttribute("websiteForm") Website websiteForm) { mm.put("websiteForm", new Website()); mm.put("publishers", publisherService.getAll()); return "website/add"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String add(@ModelAttribute("websiteForm") Website websiteForm, BindingResult result, ModelMap mm) { websiteValidator.validate(websiteForm, result); if (result.hasErrors()) { return "error"; } if (websiteForm.getWebsiteId()>0) { websiteService.edit(websiteForm); }else { websiteService.add(websiteForm); } return "redirect:index"; }
我已经将选择标记的路径从publisher
者更改为publisher.publisherId
,如下所示,来自Shantaram Tupe,但无法生成表单到html。 我从publisher
者更改为publisher.publisherName
,一切看起来都很好,表单可以在html中查看,值在publisher.publisherName
回服务器。 我怎样才能将它publisher.publisherId
回publisher.publisherId
? 我的publisherId字段的配置看起来有问题吗?
更新2
我的问题是仅生成HTML表单。 我尝试在浏览器上编辑生成的html表单,例如:
类似于:
一切都运作良好。 现在,我如何使用publisher.publisherId
生成表单?
最后更新
最后,我发现了它。 它适用于PublisherName但不适用于PublisherId,因为PublisherName是字符串类型。 我使用的select标签中的转储项(
NONE
– 不能是long类型值。 将其更改为0
并成功生成表单。
只需将
标记中的路径从publisher
更改为publisher.publisherId
我身边的其他一些事情:
-
你不需要使用
@Column(name="websiteId", nullable=false, unique=true)
- 由于您在数据库中的列名与Entity类中的字段名相同
- 由于它是用
@Id
注释的,它永远不会为null ,默认为uniqe
-
您不需要在两侧使用@JoinColumn ,在
@OneToMany
端使用mappedBy属性,例如@OneToMany(mappedBy="publisher")