有没有办法在Hibernate中使用像sql-server一样的分析函数?
就像是
select foo from Foo foo where f.x = max(f.x) over (partition by f.y)
您是在本机SQL查询之后。
如果您使用的是JPA,则语法为:
Query q = em.createNativeQuery("select foo.* from Foo foo " +
"where f.x = max(f.x) over " +
"(partition by f.y)", Foo.class);
如果需要返回多个类型,请查看SQLResultSetMapping批注。
如果您直接使用Hibernate API:
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);
见10.4.4。 有关详细信息,请参阅Hibernate文档中的本机SQL查询 。
在这两个API中,您可以使用setParameter正常传递参数。
另一种方法是使用映射。 请参阅此文章: https : //forums.hibernate.org/viewtopic.php?f = 1&t = 998482
我反对在Hibernate中使用本机SQL查询...你失去了映射的好处:-)
是的,你可以,但你需要扩展hibernate方言,如下所示:
import org.hibernate.dialect.Oracle10gDialect;
public class ExtendedDialect extends Oracle10gDialect{
public ExtendedDialect()
{
super();
registerKeyword("over");
registerKeyword("partition");
}
}
一旦这个类在你的类路径上,你需要告诉hibernate使用它而不是原始的方言(在这种情况下是Oracle10gDialect)。 我不确定您使用的是哪些框架,但在Spring的情况下,您可以在LocalContainerEntityManagerFactoryBean下使用以下属性:
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="path.to.dialect.ExtendedDialect" />
</bean>
</property>
然后你可以在@Formula注释,@ Where注释和其他hibernate功能中使用over和partition,而不会混淆hibernate。