简体   繁体   中英

Hibernate criteria API querying inheritance issue

Lets say that class 'X' is mapped to table 'X' class 'A' is mapped to Table 'A' and Class 'B is mapped to table 'B'.

Table X Structure:(X_ID, some other columns Table A Structure:(A_Id,X_Id, some other columns) Table B Structure:(A_Id, some other columns)...Table B also has A_Id

Class 'B' extends class 'A'. We have the mapping files for both of them as:

Class 'A' Parent Mapping file:

@Entity
@Table(name = 'A')
@Inheritance(stratergy=InheritanceType.Joined)
public abstract class A {
@Id @Clumns(name = "A_Id)
@GeneratedValue
protected Long aId;
-- some more A specific fields
}

Class 'B' Mapping file:

@Entity
@Table(name= 'B')
Public class B extends A{
---- B specific fields
}

Now, I have a SQL Query as below that I need to write using hibernate criteria API.

select * from X
INNER JOIN A 
ON X.id = A.id
INNER JOIN B
ON A.id = B.id
where B.name = 'XYZ'
   and B.Sex = 'M'

I have come up with:

Criteria c = session.createCriteria(x.class, "x");
                    .createAlias("x.a", "a")
                    .createAlias("a.b", "b")          
                    .add(Restrictions.eq("b.sex", "M"))
                    .add(Restrictions.eq("b.name", "XYZ"));

But, if we check the mapping file, there is no direct reference of B in A. Hence hibernate throws out "B not related to A" entity.

Is there any way this inheritance can be mapped in query crteria

B is-a A. So you don't need to make any join between A and B. Hibernate does that for you:

Criteria c = session.createCriteria(x.class, "x");
                    .createAlias("x.a", "b")
                    .add(Restrictions.eq("b.sex", "M"))
                    .add(Restrictions.eq("b.name", "XYZ"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM