我正在使用 Java Playframework 2.1.1 并尝试创建一个表单来保存具有多对多关系(学生和类(class)之间)的对象。在我看来要创建一个学生,因此我使用多选元素来选择多门类(class)。提交表格后,学生被正确插入,但可连接的“学生类(class)”仍然是空的。
这是一些代码:
类(class).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">
}
}
感谢任何帮助!
最佳答案
我现在通过自己将值绑定(bind)到对象解决了这个问题。
这是来 self 的 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() 函数时,我仍在寻找一种更优雅的方法来执行此操作。
关于java - 使用 Playframework 持久化多对多对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17330454/