我的程序要求是在数据库中添加一个新的父级和子级。到目前为止,我在父类中有这个方法:
@Transient
public void addLecturer(Lecturer lecturer) {
if(lecturers == null) {
lecturers = new ArrayList<Lecturer>();
}
lecturer.setChecker(this);
this.lecturers.add(lecturer);
}
然后在我的父级中保存父级:
@Override
public void addChecker(Lecturer checker) {
Session session = sessionFactory.getCurrentSession();
session.save(checker);
}
我的控制器:
@RequestMapping(value="/matching_page", method = RequestMethod.GET)
public ModelAndView get(@ModelAttribute("checker") Lecturer checker, BindingResult
result) {
ArrayList<String> lecturers = new ArrayList<String>();
lecturers.add("Somma");
lecturers.add("Trina");
lecturers.add("Adam");
lecturers.add("Eve");
HashMap<String, ArrayList<String>> model = new HashMap<String
ArrayList<String>>();
model.put("lecturerList", lecturers);
return new ModelAndView("matching_page", "model", model);
}
@RequestMapping(value="/matching_page", method = RequestMethod.POST)
public ModelAndView hello(@ModelAttribute("checker") Lecturer checker,
BindingResult result) {
lecturerService.addChecker(checker);
return new ModelAndView ("redirect:/admin");
}
jsp形式:
<c:url var="saveUrl" value="/matching_page" />
<form:form modelAttribute="checker" method="POST" action="${saveUrl}">
<td>Checker </td>
<tr>
<td><form:hidden path="lecturerId" value="" /></td>
</tr>
<tr>
<td><form:label path="name">Checker Name:</form:label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email"/></td>
</tr>
<td>Lecturers</td>
<td>
<form:select path="name" multiple="true">
<form:option value="0" >Select </form:option>
<form:options items="${model.lecturerList}" />
</form:select>
</td>
<div id="lower">
<input type="submit" value="Save Selection" class="button"/>
</div>
</form:form>
我的数据库:
CREATE TABLE `lecturers` (
`lecturer_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT NULL,
`email` VARCHAR(255) NULL DEFAULT NULL,
`checker_id` BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`lecturer_id`),
FOREIGN KEY (`checker_id`) REFERENCES `lecturers` (`lecturer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
我的模型
@Entity
@Table(name = "lecturers")
@Component
public class Lecturer implements Serializable{
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="checker_id")
private Lecturer checker;
@OneToMany(mappedBy="checker", orphanRemoval=true)
private List<Lecturer> lecturers = new ArrayList<Lecturer>();
}
表单绑定了一个父对象(检查器),我想添加一个或多个从选择列表中选择并保存的子对象。
保存有效,但它将所有新对象保存为子对象,并且不会使用检查器 ID 单独保存检查器父对象。我不确定问题是什么并且想知道。