0

I'm having trouble getting a list of related entity objects as the result of a criteria expression. I have two objects with a many to many relationship such that ObjectA <-> ObjectB where a single instance of ObjectA can be tied to a multiple instances of ObjectB, and an instance of ObjectB maybe tied to multiple instances of ObjectA. This relationship is stored in your typical join table, but for legacy reasons the object model is such that ObjectB has no direct knowledge of it's relationship to ObjectA. I'm trying to create a criteria expression to get all of the instances ObjectB that are related to any ObjectA through the join table object with the following:

getDetachedCriteria(ObjectAObjectB.class)
.setFetchMode("objectB", FetchMode.JOIN)
.setProjection(Projections.property("objectB"));

However this doesn't work as expected, as it appears the Projection API only supports projecting scalar properties and not Entity Objects. Is it possible to specify this type of selection through Projections or some other Criteria API?

Clayton
  • 5,330
  • 1
  • 18
  • 15
  • Correct me if I'm wrong but your mapping is ObjectA N <--> 1 ObjectB so you should use a ManyToOne ? – overmeulen Feb 20 '13 at 09:19
  • @overmeulen Sorry I misrepresented the problem, I've updated my post to correct some errors. The relationship is actually many to many, but the query is based off of the join table. – Clayton Feb 21 '13 at 01:09
  • Could you show us your mapping ? Can't you make ObjectB aware of its relationship with ObjectA using a bidirectional mapping ? It won't change your database schema and it will make things so much easier ! – overmeulen Feb 21 '13 at 09:47
  • I agree with overmeulen. I deleted my previous answer. We need to see mappings or else we are shooting in the dark. There has to be a way to map this better. – carbontax Feb 21 '13 at 13:17

1 Answers1

2

You can't do that with the Hibernate Criteria API. It's possible in HQL or in the JPA2 Criteria API, but not using the Hibernate Criteria API.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • @JB Nizet, how we can archieve that with HQL? – Victor Jun 06 '14 at 16:38
  • 1
    @Victor: `select distinct objectB from ObjectA objectA join objectA.collectionOfBs objectB where ...` – JB Nizet Jun 06 '14 at 17:59
  • Ey @JBNizet, first at all, thanks!, second : check out my recent post here http://stackoverflow.com/questions/24087605/hibernate-criteria-projection-of-non-scalar-values, perhaps you can answer there! – Victor Jun 06 '14 at 18:04