If you have simple associations like this:

@Entity
@Table
public class ClassEntity {

    @OneToMany(mappedBy = "class")
    private Set<StudentEntity> students = new HashSet<>();
}

@Entity
@Table
public class StudentEntity {

    @ManyToOne
    private ClassEntity class;

    // All students must have a course
    @ManyToOne(optional = false)
    private CourseEntity course;

}

But when you load a class entity and the students is an empty set and you are sure there are records in the students table with correct class_id, then the problem could be with one of the other associations in StudentEntity class.

Eg. course is set to optional as false so it is expected to be a non-null field in the DB. So if the student records have null values in course_id, then when you load class records, it won’t have any students without a course because Hibernate is doing an INNER JOIN instead of a LEFT JOIN. To fix, either remove the optional value to make it optional true by default, or make the course_id column non-nullable.

Leave a Reply

Your email address will not be published. Required fields are marked *