3

我正在使用 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">
}

}

任何帮助表示赞赏!

4

1 回答 1

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);

我仍在寻找一种更优雅的方式来执行此操作,同时使用 fillForm.get() 函数。

于 2013-06-29T13:33:19.313 回答