我正在使用Java Playframework 2.1.1并尝试创建一个表单来持久化具有多对多关系的对象(在学生和课程之间)。在我创建学生的观点中,我因此使用多选元素来选择多个课程。提交表格后,学生会正确插入,但加入表“学生课程”仍为空。
以下是一些代码:
Course.java
@Entity
public class Course extends Model {
...
@ManyToMany(mappedBy = "courses", cascade=CascadeType.ALL)
private List<Student> students;
public static List<Course> find() {
Query query = JPA.em().createQuery("SELECT e FROM course e");
return (List<Course>) query.getResultList();
}
...
}
Student.java
@Entity
public class Student extends Model {
...
@ManyToMany(cascade = CascadeType.ALL)
private List<Course> courses;
...
}
AdminController.java
public class Admin extends Controller {
final static Form<Student> studentForm = Form.form(Student.class);
@Transactional
public static Result newStudent(){
List<Student> students= Student.find();
return ok(createStudent.render(students,studentsForm));
}
@Transactional
public static Result submitStudent(){
Form<Student> filledForm = studentForm.bindFromRequest();
if(filledForm.hasErrors()) {
Logger.error("Submitted Form got errors");
return badRequest();
} else {
Student student= filledForm.get();
Student.save(student);
}
List<Student> students= Student.find();
return ok(createStudent.render(students,studentForm));
}
...
}
创建学生的表格:
@(students:List[Student], studentForm: Form[Student])
@import helper._
@main("Administration - Create Student"){
<h1>Create Student</h1>
<hr/>
}
<h2>New Student</h2>
@helper.form(action = routes.Admin.submitStudent) {
...
@helper.select(studentForm("courses"),
options(Course.options),
'multiple -> "multiple",
'_label -> "Course")
<input type="submit" class="btn btn-success">
}
}
感谢任何帮助!
答案 0 :(得分:1)
我现在通过将值绑定到对象来解决问题。
以下是我的Admincontroller中的代码:
Student student = filledForm.get();
List<Student> courses= new LinkedList<Course>();
for(Map.Entry<String, String> entry : filledForm.data().entrySet()){
if(entry.getKey().contains("courses")){
Course c = Course.find(Long.parseLong(entry.getValue()));
courses.add(c);
}
}
student.setCourses(courses);
在使用filledForm.get()函数时,我仍然在寻找一种更优雅的方法。