Question

I have a generic criteria query and it returns same records. I think there is something wrong with my student save method. Here is my save method;

    Student student = new Student();
    student.setId(Utility.generateUUID());
    student.setClassroom(selectedClassroom);
    student.setUrl(urlAddress);
    genericService.save(student);

When I try to get all Classrooms from datatable it returns 3 Classroom object which are same but there is only one record in Classroom table. The Problem is there are 3 student records which Classrooms are referencing to this classroom record.

My criteria query;

    @Transactional(readOnly = true)
public <T> List<T> getByTemplate(T templateEntity) {
    Criteria criteria = getCurrentSession().createCriteria(templateEntity.getClass());
    criteria.add(Example.create(templateEntity));
    return criteria.list();
}

Entities;

public class Classroom{

    ....
    @OneToMany(mappedBy = "classroom", fetch = FetchType.EAGER)
    private List<Student> studentList;
}


public class Student{

    @JoinColumn(name = "classroom", referencedColumnName = "id")
    @ManyToOne(fetch = FetchType.LAZY)
    private Classroom classroom;
}
Was it helpful?

Solution

Try to add the following to your criteria:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

This will retrieve distinct entities for Classroom even tought the inner join select will retrieve the three lines (one per user).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top