Sachin
Sachin

Reputation: 459

@OneToMany shows duplicate values for collection variable

I am getting filtered 'Trainer' entities, but collection (trainedMonkeys) is not filtered. 'trainedMonkeys' variable is holding all 'Monkey' objects instead of holding only the one with 'isThumb = true'.

Can someone please check if below criteria I am using is correct?

@SuppressWarnings("unchecked")
    public List<Trainer> listTrainers() {         
        Criteria crit = sessionFactory.getCurrentSession().createCriteria(Trainer.class)
        .createAlias("trainedMonkeys", "tm")
        .add(Restrictions.eq("tm.isThumb", true))
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Trainer.java

public class Trainer {  
    private Long trainerId;

    private String trainerName;

    public List<Monkey> trainedMonkeys;

Monkey.java

public class Monkey {

    private Long id;

    private String monkeyName;  

    private boolean isThumb;

I am executing below code in the controller,

for (Trainer trainer : trainerList){  
            System.err.println("<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>");  
            System.err.println("Trainer ID*****"+trainer.getTrainerId());  
            System.err.println("Trainer Name******"+trainer.getTrainerName());  
            monkeyList = trainer.getTrainedMonkeys();  
            for (Monkey monkey : monkeyList){  
                System.err.println("Monkey ID*****"+monkey.getId());  
                System.err.println("Monkey Name*****"+monkey.getMonkeyName());  
            }  
            System.err.println("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>");  
        }

and the output is as below (Monkey_2 and Monkey_6 are the only objects that should be present as only they satisfy the criteria) please help,

<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> 
Trainer ID*****88 
Trainer Name******TrainerSachin 
Monkey ID*****87 
Monkey Name*****Monkey_1 
Monkey ID*****88 
Monkey Name*****Monkey_2 
Monkey ID*****89 
Monkey Name*****Monkey_3 
<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>> 
<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> 
Trainer ID*****89 
Trainer Name******TrainerVinod 
Monkey ID*****90 
Monkey Name*****Monkey_5 
Monkey ID*****91 
Monkey Name*****Monkey_6 
Monkey ID*****92 
Monkey Name*****Monkey_7 
<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>> 

Upvotes: 1

Views: 208

Answers (1)

Mikko Maunu
Mikko Maunu

Reputation: 42114

It should hold all. You misinterpret Criteria restrictions. Restrictionss filter which criterias returned entities should meet. They do not filter elements out from the collections in returned entities.

Query returning entity with subset of relations to related entities would make things complex. Think about what should happen when such an entity is merged back to database.

More details about subject can be found from Hibernate documentation.

Upvotes: 1

Related Questions