Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use analytic functions in Hibernate?

Tags:

sql

hibernate

Is there a way to use sql-server like analytic functions in Hibernate?

Something like

select foo from Foo foo where f.x = max(f.x) over (partition by f.y)
like image 397
ncgz Avatar asked Sep 16 '08 16:09

ncgz


People also ask

Can we write SQL query in hibernate?

You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3. x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

What is analytics function in SQL?

Analytic functions calculate an aggregate value based on a group of rows. Unlike aggregate functions, however, analytic functions can return multiple rows for each group. Use analytic functions to compute moving averages, running totals, percentages or top-N results within a group.


1 Answers

You are after a native SQL query.

If you are using JPA the syntax is:

Query q = em.createNativeQuery("select foo.* from Foo foo " +
                               "where f.x = max(f.x) over " +
                               "(partition by f.y)", Foo.class);

If you need to return multiple types, take a look at the SQLResultSetMapping annotation.

If you're using the the Hibernate API directly:

Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
                                 "where f.x = max(f.x) over "+
                                 "(partition by f.y)");
q.addEntity("foo", Foo.class);

See 10.4.4. Queries in native SQL in the Hibernate documentation for more details.

In both APIs you can pass in parameters as normal using setParameter.

like image 112
Jason Weathered Avatar answered Oct 15 '22 20:10

Jason Weathered