有没有办法在Hibernate中使用类似sql-server的分析函数?
像
这样的东西select foo from Foo foo where f.x = max(f.x) over (partition by f.y)
答案 0 :(得分:7)
您正在使用本机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);
有关详细信息,请参阅Hibernate文档中的10.4.4. Queries in native SQL。
在这两个API中,您可以使用setParameter正常传递参数。
答案 1 :(得分:4)
另一种方法是使用映射。请参阅此文章:https://forums.hibernate.org/viewtopic.php?f=1&t=998482
我反对在Hibernate中使用本机SQL查询...你失去了映射的好处: - )
答案 2 :(得分:3)
是的,你可以,但你需要扩展hibernate方言,如下所示:
import org.hibernate.dialect.Oracle10gDialect;
tmp/www
一旦这个类在你的类路径上,你需要告诉hibernate使用它而不是原来的方言(在本例中是Oracle10gDialect)。我不确定您使用的是哪些框架,但在Spring的情况下,您可以在LocalContainerEntityManagerFactoryBean下使用以下属性:
public class ExtendedDialect extends Oracle10gDialect{
public ExtendedDialect()
{
super();
registerKeyword("over");
registerKeyword("partition");
}
}
然后你可以在@Formula注释,@ Where注释和其他hibernate功能中使用over和partition,而不会混淆hibernate。