使用Hibernate& SQL来检查数据库中是否存在一行的最快方法是什么?弹簧? [英] What's the fastest way to check if a row exists in DB using Hibernate & spring?

查看:68
本文介绍了使用Hibernate& SQL来检查数据库中是否存在一行的最快方法是什么?弹簧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以非常快的方式检查数据库中是否存在一行。
假设我有主键。
我在Hibernate的常见问题网站上找到了这段代码:

  Integer count =(Integer)session.createQuery(select count(*)from ....)。uniqueResult(); 

我刚开始使用spring,所以我将HibernateTemplate对象注入到了我的类中。
如何翻译此代码段以使用HibernateTemplate。



有人知道比这更好/更快的方式吗?

感谢。

解决方案

  Long count = hibernateTemplate.execute HibernateCallback< Long>(){
@Override
public Long doInHibernate(Session session){
return(Long)session.createQuery(SomeEntiuty someEntity中的select count(someEntity.id).. )。uniqueResult();
}
});

之前Hibernate使用Integer进行count查询,但现在使用Long。另外,请注意,即使不被弃用,Spring建议不要再使用HibernateTemplate,并直接使用Hibernate API(使用 sessionFactory.getCurrentSession())。


I need to check if a row exists in a database in a very fast way. Let's say I've got the primary key. I found this code snippet in Hibernate's FAQ website:

Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();

I just started using spring, so I have HibernateTemplate object injected into my class. How do I translate this snippet to work with HibernateTemplate.

Does anyone knows a better/faster way than this ?

Thanks.

解决方案

Long count = hibernateTemplate.execute(new HibernateCallback<Long>() {
    @Override
    public Long doInHibernate(Session session) {
        return (Long) session.createQuery("select count(someEntity.id) from SomeEntiuty someEntity ...").uniqueResult();
    }
});

Hibernate used Integer for count queries before, but now uses Long. Also, note that even if not deprecated, Spring recommends not to use HibernateTemplate anymore and use the Hibernate API directly (using sessionFactory.getCurrentSession()).

这篇关于使用Hibernate&amp; SQL来检查数据库中是否存在一行的最快方法是什么?弹簧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆