JavaSpringMVC/JSTL/JPA集成:使用SpringMVC更新现有子元素并向父实体添加新的子元素
我是SpringMVC和JPA的新手。我正在用这些框架做一个学生项目。在这个项目中,我想实现一个JSP来更新现有的子元素,并向父实体添加新的子元素。 我的解决方案奏效了。但我认为应该有一种更优雅或“标准”的方式来做到这一点。以下是我的代码:
JPA实体
@Entity
public class Parent {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Child> children = new HashSet<Child>();
// constructors, getters and setters
}
@Entity
public class Child{
@Id
@GeneratedValue
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parentId")
private Parent parent;
private String name;
// constructor getter and setter
}
命令名类
public class CommandName {
private Parent parent;
private List<Child> existingChildren = new ArrayList<Child>();
private List<Child> newChildren = new ArrayList<Child>();
private static final int MAX_NUM_NEW_CHILDREN = 3;
public CommandName(Parent parent) {
this.parent = parent;
this.existingChildren.addAll(parent.getChildren());
for (int i = 0; i < MAX_NUM_NEW_CHILDREN; ++i) {
newChildren.add(new Child());
}
}
// getters and setters
}
控制器类
@Controller
public class MyController {
@Autowired
private ParentRepository parentRepository;
@RequestMapping(value = "/editParent/{parentID}", method = RequestMethod.GET)
public String editParent(ModelMap model, @PathVariable("parentID") Integer parentID) {
CommandName cn = new CommandName(parentRepository.findOne(parentID));
model.addAttribute("cn", cn);
return "edit";
}
@RequestMapping(value = "/saveParent", method = RequestMethod.POST)
public String saveParent(CommandName cn, BindingResult bindingResult) {
Parent parent = cn.Parent();
List existChildren = cn.getExistingChildren();
for (Child c : existChildren) {
c.setParent(parent);
}
List newChildren = cn.getNewChildren();
for (Child c: newChildren) {
c.setParent(parent);
}
parent.getChildren().addAll(existChildren);
parent.getChildren().addAll(newChildren);
parentRepository.save(parent);
return "redirect:/view";
}
}
编辑中的表单。jsp
<f:form role="form" action="/saveParent" commandName="cn">
<f:hidden path="parent.id"/>
<f:label path="parent.name">Parent Name</f:label>
<f:input type="text" path="parent.name"/>
<label>Children</label>
<c:forEach items="${cn.existingChildren}" var="child" varStatus="status">
<f:hidden path="child.id"/>
<f:input type="text" path="existingChildren[${status.index}].name"/>
</c:forEach>
<c:forEach items="${cn.newChildren}" var="child" varStatus="status">
<f:input type="text" path="newChildren[${status.index}].name"/>
</c:forEach>
<button type="submit">Submit</button>
</f:form>
这些代码集起作用了:父级和现有子级被更新。新的孩子们被创造出来了。但是在saveParent()方法中,我必须执行以下操作来重新链接所有内容。有没有更好的方法(更好的commandName类,更好的jsp表单?)非常感谢
List existChildren = cn.getExistingChildren();
for (Child c : existChildren) {
c.setParent(parent);
}
# 1 楼答案
正如在你的问题中,你没有更新的父母,也没有必要去嘲笑现有的孩子。。只添加新的孩子。。所以 将
/saveParent
帖子更改为:致: