我正在使用 Java Playframework 2.1.1 并尝试创建一个表单来保存具有多对多关系(学生和课程之间)的对象。在我看来要创建一个学生,因此我使用多选元素来选择多个课程。提交表格后,学生被正确插入,但可连接的“学生课程”仍然为空。
这是一些代码:
课程.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();
}
...
}
学生.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">
}
}
任何帮助表示赞赏!