mjs
mjs

Reputation: 22369

Hibernate criteria, selecting from entity A where someId in B

Given entity classes:

class A { String name ... } 
class B { @OneToOne A a = ... ;  String gender; ... } 

I am able to create a hibernate criteria and query it and all of it's associations.

However, B is not referenced from A at all. It's populated in a separate fashion and I would like to keep it as such.

Is there a way to perform a hibernate criteria query on A, and say, where this also is in B's relation, or where it is in B's relation and some field in B is this and that?

Here is some non-working pseudo code:

criteria(A.class).add(
        Restrictions.eq("name", "something")
).createAlias(
        B.class, "..."
).add(
        Restrictions.eq("gender", "Female")
);

Note, I would prefer not having to create a collection on A containing B's and using addAll.

I might consider adding a dead reference though, meaning something that is never intended to be accessed or updated but needed for hibernate to pull this off. It could be something like saying that this is maintained by another table.

Upvotes: 0

Views: 232

Answers (1)

IntelliData
IntelliData

Reputation: 432

You can use a subquery, as follows:

// create a 'DetachedCriteria' query for all the items in 'B'
DetachedCriteria dc = DetachedCriteria.forClass(B.class).setProjection(
    Projections.projectionList().add(Projections.property("propertyInB")) 
);

// then: search for A.id by adding 'dc' as asubquery:        
session.createCriteria(A.class).add(
    Subqueries.propertiesIn( new String[]{"propertyInA"}, dc)
).list();

This is roughly equivalent to: 'SELECT * FROM A a WHERE a.id in(SELECT id FROM B).

I hope my SQL is valid ;) .

See hibernate documentation: https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querycriteria.html

Upvotes: 1

Related Questions