Saskia
Saskia

Reputation: 1056

Automatically updating Many-to-Many tables with unique coloumns

while I wrote this question I figured out a solution but I'm going to ask anyway. Maybe there's an easier way to do it.

I want to make an association table from two tables. Let's call them Student and Course. Both have an id and an unique name.
What I want is a third table (student_id to course_id) wich is automatically updated when i insert a student who's attending courses.

It is almost the following example i found here: Hibernate Many-to-Many with Annotations but i changed the @Table annotation to
@Table(name = "STUDENT", uniqueConstraints = {@UniqueConstraint(columnNames = {"STUDENT_NAME" })})
The same for Courses.

I insert a first student

Set<Course> courses = new HashSet<Course>();
courses.add("Math); courses.add("Science");

Student alice = new Student("alice", courses);

Here comes another Student

Student bob= new Student("bob", courses);

And it crashes becauses the courses science and math already exists in the table courses and the student_to_course table will not be updated.

What I'm doing know is to query for a course with this name in the course table. If there is one i add it to the students course otherwise add a new one.

List<Course> list = session.createCriteria(Course.class)
            .add(Restrictions.eq("courseName", "Maths")).list();
if (list.size() > 0){
   courses.add(list.get(0));
}
else {
    courses.add(new Course("Maths"));           
}
s.setCourses(courses);

So this works, but I think there must be a better way to do it.
Is there a way to tell hibernate to add the courses to the student from the courses table if there already is a course with the same name in the table?

Upvotes: 0

Views: 87

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

You're doing it correctly, and there's no other way.

Except this scenario is not very realistic. Most of the time, the list of available courses is known in advance, and you may only pick among the available courses when you create a student. The UI will typically propose a multi-select box where you'll have to select courses, and you won't refer to the chosen courses using their name, but using their ID (or using the Course entity directly).

The method will thus look like this:

public Student createStudent(String studentName, Set<Long> courseIds)

or like this:

public Student createStudent(String studentName, Set<Course> courses)

In the first case, the easiest and fastest way to get a set of course is to loop over the course IDs and call session.load(courseId) to get a reference to the course, without even needing to hit the database.

Upvotes: 0

Related Questions