Question

EDIT> i am at a dead end... so i can continue looking for the main reason .. Please tell me how to make a simple criteria for many to many relationships which has more than one eq restrictions, for an example, how to get the person speaking eng & german in the example shown here...

My situation is like this i have two classes person and languages, with a n,m relationship.. And i am using a criteria to do the search - get all the persons which speak ex. English and German

@Entity
public class Person implements Serializable {
    private int id;
           ...........
    private Set<Languages> languages = new HashSet<Languages>();
       ...............
    @ManyToMany
    @JoinTable(name = "link_person_languages")
    public Set<Languages> getLanguages() {
       return languages;
    }
}

@Entity
public class Languages implements Serializable {
    private int id;
    private String name;
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    @Column(nullable = false, length = 40, unique = true)
    public String getName() {
        return name;
    }

Criteria

    Criteria crit = session.createCriteria(Person.class);
    crit.setCacheable(true);
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.property("languages"));
    c = enumMap.get(attr);
    if (c.isChanged()) {
       Criteria crit2 = crit.createCriteria("languages");
       Object[] o = (Object[]) c.getAnswer();
       Conjunction con = Restrictions.conjunction();
       for (int j = 0; j < o.length; j++) {
              Criterion tmp = Restrictions.eq("id", ((Languages)o[j]).getId());
              con.add(tmp);
       }
       crit2.add(con);

    }
    crit.setProjection(projList);
    retList = crit.list();

And the funny thing is, if i set it only for one language, i get the proper list of persons, but for more than one language i get none, i rechecked my base and set one person specifficaly to speak the 2 languages. But what tips mi more than anything is that the result from the projection in the Object[] on the place where the Set languages should be, there is NULL value......

please help tnx

Was it helpful?

Solution

What you are doing in very old JDBC style (JDBC is what very old people used to access DB) would be something like this:

SELECT * FROM PERSON WHERE LANGUAGE_ID = 1 AND LANGUAGE_ID = 2

(just example, not exactly SQL)

And, if you run this sql it will NEVER return a single line (Very sad...) because there is no line in the table with LANGUAGE_ID = 1 AND LANGUAGE_ID = 2.

I don't really know the best way to solve your problem (Hibernate is not my strongest skill), but in your case (if the languages number is not so big) i would make 2 (or 3, or a loop) of selections and join then using a simple Set in code. Not the best solution... And i will happy if someone show a better way

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