Is it possible to use analytic functions in Hibernate?

后端 未结 3 886
我寻月下人不归
我寻月下人不归 2021-02-13 04:56

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         


        
相关标签:
3条回答
  • 2021-02-13 05:25

    Another approach would be to use the mapping. Please see this article: https://forums.hibernate.org/viewtopic.php?f=1&t=998482

    I am against the usage of native SQL queries in Hibernate... you lose the benefits of having a mapping:-)

    0 讨论(0)
  • 2021-02-13 05:29

    Yes you can, but you will need to extend the hibernate dialect like the following:

    import org.hibernate.dialect.Oracle10gDialect;

    public class ExtendedDialect extends Oracle10gDialect{
        public ExtendedDialect()
        {
               super();
               registerKeyword("over");
               registerKeyword("partition");
        }
    }
    

    Once this class is on your classpath, you will need to tell hibernate to use it instead of the original dialect (in this case Oracle10gDialect). I am not sure which frameworks you are using, but in the case of Spring, you can use the following property under the LocalContainerEntityManagerFactoryBean:

            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="databasePlatform" value="path.to.dialect.ExtendedDialect" />
                </bean>
            </property>
    

    Then you can use over and partition in @Formula annotations, @Where annotations and other hibernate features without confusing hibernate.

    0 讨论(0)
  • 2021-02-13 05:34

    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.

    0 讨论(0)
提交回复
热议问题