有没有办法在 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 查询......你失去了拥有映射的好处:-)
是的,你可以,但你需要像下面这样扩展休眠方言:
导入 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。