Search code examples
sqlhibernatecriteria

Criteria API query generation


I have a pretty straight forward task to query table and filter using some parameter (this parameter is foreign key for other table).

As example Table1 contains following fields:

id, name , description, company_id;

I have a method that takes as input company_id (not company object) and returns all records from table1. The criteria query looks as follows:

DetachedCriteria criteria = DetachedCriteria.forClass(Table1.class)
       .add(Restrictions.eq("company.id", companyId));

The problem is that generated query is too complex because it joins a couple of tables to do this. And this query is not "production ready"

Is there any way to build criteria to have SQL query like this?:

SELECT * from table1 where company_id =?

Solution

  • I suppose you use EAGER instead of LAZY fetch on some your object mapping. If you don't actually need EAGER use LAZY and it should generate more simple query with your DetachedCriteria.