Devour
Devour

Reputation: 335

Criteria returns same object several times

I have 3 tables with many-to-many relations. User, Compurets and the third table is User_Comp that connects others. One User can have several computers assigned through id to him. So there are several entities of User in table there.

Here is my table:

enter image description here

For getting all users this method gives correct data.

public List<User> getAllUsers() {
        Session session = HibernateUtil.openSession();
        return session.createQuery("from User").list();
}

But when I use method with Criteria such as:

    public List<User> getAllUsers() {
    return currentSession().createCriteria(User.class).list();

it returns several same records as shown at the picture. As I could understand it uses table User_Comp, because iterator returns:

User {Id= '1', login= 'user1', password= '1', name= 'userOne'…
User {Id= '2', login= 'user2', password= '2', name= 'userTwo'…
User {Id= '3', login= 'user3', password= '3', name= 'userThree'…
User {Id= '3', login= 'user3', password= '3', name= 'userThree'…
User {Id= '3', login= 'user3', password= '3', name= 'userThree'…
User {Id= '3', login= 'user3', password= '3', name= 'userThree'…
User {Id= '4', login= 'user4', password= '4', name= 'userFour'…
User {Id= '5', login= 'user5', password= '5', name= 'userFive'…

Question: what I have to do in order to get data from table Users or get unique record for each User?

Upvotes: 1

Views: 585

Answers (1)

Lorenzo Boccaccia
Lorenzo Boccaccia

Reputation: 6131

I guess the user>computer relation is not set as lazy so it loads up all the computer in a outer join to populate the getComputers from the user

you can use

 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

to only iterate trough each entity once

Upvotes: 3

Related Questions