Search code examples
hibernatehibernate-mappinghibernate-criteriacomposite-id

hibernate Criteria on Composite Id


Below is the same code very similar to my code where i am facing the issue

//mapped to Table B
class B implements Serializable {
   //Primary key bId
   private Long bId;
   //Getter and setter for bId;
}

//Mapped to table C
class C implements Serializable {
   //Primary key bId
   private Long cId;
   //Getter and setter for cId;
}

//mapped to Table A (Which has composite key fBid and fCid)
class A{
   //Composite primary key
   private B bid;
   private C cid;
   //getter and setter for B and C
  //Other fields

}

If I will create a criteria like below :-

B b = new B();
b.setBId(1l);

C c = new C();
c.setCId(2l);

Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(A.class,"a");
        criteria.add(Restrictions.eq("a.bid", b));
        criteria.add(Restrictions.eq("a.cid",c));
        A result = (A) criteria.uniqueResult();
        return result;

I am getting below exception

org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = bytea

even i created a separate class BC which has object of B and C class and used this in class A as composite key. and then did a

 Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(A.class,"a");
            criteria.add(Restrictions.eq("a.BC", bc));
            A result = (A) criteria.uniqueResult();
            return result;

Still same error

any Help will be appreciated.

Note :- I am doing hibernate xml maping for all the classes.



solution that i have found changed the class A like below :-

class A{
private BC bc;
//getter and setter 
}

where BC

class BC{
 private B b;
Private C c;
//getter and setters 
}

Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(A.class,"a");
        criteria.add(Restrictions.eq("bc.b", b));
        criteria.add(Restrictions.eq("bc.c",c));
        A result = (A) criteria.uniqueResult();
        return result;

Solution

  • the error is indicating , that you are trying to compare 2 different things. "a.bc" will return the blob object and bc inside java will give you the actual pointer value. You can change the restriction with

    criteria.add(Restrictions.eq("a.bId.bId", b.bId));
    criteria.add(Restrictions.eq("a.cid.cId",c.cId));
    

    Note that this will work , because you are defining the Criteria Class with createCriteria(A.class,"a") so "a" will be the Alias for the A Class

    For More info , check this answer