Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting ManyToMany-Objects using Playframework

I am using Java Playframework 2.1.1 and try to create a form to persist objects that have a many-to-many relationship (between student and course). In my view to create a student, I am therefore using a multiselect-element to choose multiple courses. After submitting the form, the student gets inserted correctly, but the jointable "student-course" remains empty.

Here is some code:

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

The form to create a student:

@(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">
}

}

Any help is appreciated!

like image 503
Martin Golpashin Avatar asked Jan 23 '26 02:01

Martin Golpashin


1 Answers

I've solved the problem now by binding the values to the object myself.

Here is the code from my 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);

I am still looking for a more elegant way to do this while using the filledForm.get() Function.

like image 179
Martin Golpashin Avatar answered Jan 25 '26 16:01

Martin Golpashin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!