There are 2 entities:

public class Firm { private String name; } public class Contractor { private Integer inn; @ManyToOne private Firm firm; } 

I am trying to get a list of companies whose contractor’s inn is equal to a certain number. There will be a list of Inn (so there may be many companies).

So far I have decided to do it for 1 Inn. Trying to do this:

 criteria.createAlias("contractor", "contr"); criteria.add(Restrictions.eq("contr.inn", inn)); 

And I get an exeption org.hibernate.QueryException: could not resolve property: contractor of: Firm , which is correct in principle.

How to make a request that I need?

PS The request should be done to the Firm table.

  • one
    All the same, try and in the classroom of the company to determine the relationship with the contractors. Again, from your annotations I don’t see what an INN is - a key or just a member-given. In this regard, there are two possible cases of binding - if the key, then OneToMany, if your contractor is not an entity, but an embeddable object, then an ElementCollection. I didn’t work with the Criteria API; - smackmychi

1 answer 1

I found the answer.
We need to do another subquery.
Using Criteria does not work, you need to use DetachedCriteria.
In my case, the request will be like this:

 DetachedCriteria dc = DetachedCriteria.forClass(Contractor.class, "cont"); dc.setProjection(Projections.property("firm")); dc.add(Restrictions.eq("cont.inn",inn)); criteria.add(Property.forName("id").in(dc)); 

In general, using detachedCriteria, you can link unrelated tables in any way.

  • As I understand it, this is a request for entities that are not tied to any context (detached). - smackmychi
  • @smackmychi like yes, I found no other way, I can’t change entities anymore, i.e. Do not make reference to the contractor in the company. - whispeer
  • @whispeer design errors? - smackmychi
  • most likely, I recently began to finalize this project, perhaps I misunderstood myself somewhere. - whispeer
  • @whispeer there is no option to transfer everything to another database, correcting the entity as necessary? - smackmychi