简体   繁体   中英

Translating a SQL query with a LIMIT in a subquery to Hibernate

I want to query a database using a somewhat elaborate combination of requirements. I know how to do this with SQL, but I'm having trouble to map the results of this query in Hibernate. From experience I know there is usually a "proper Hibernate way" of doing things like this, but I'm having trouble to find it.

The data I want to extract consists of parent/child relations. Let's call the parent entity Company and the child entity Employee . The relations between the two are specified in a table called EmployeeToCompany .

The number of companies is huge, so I only want to fetch the first 10. If I would do a regular JOIN and put a LIMIT on the main query, I end up with the first 10 company/employee pairs, but I want to get all company/employee pairs for the first 10 companies . This is why I created the following SQL query:

select * from Employee
inner join CompanyToEmployee on CompanyToEmployee.employeeId = Employee.id 
inner join (
  select *
  from Company
  order by interestingness asc
  limit 0, 10
) as selectedCompany on CompanyToEmployee.companyId = selectedCompany.id 
order by selectedCompany.interestingness asc, Employee.lastName asc, Employee.firstName asc

I'm running this query from Hibernate using Session.createSQLQuery, but I find it hard to map these results. The problem is that I want to map the results back to both Employee and Company entities. I have managed to do this by creating a custom ResultTransformer , but the result is very inelegant and I think there should be a better way.

Using native SQL query you can write and SQL join. So, my ideea is: Map the join collection (OneToMany) in entity. Use query.addJoin() to map result, see here Chapter 16.1.3

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