在Hibernate注释下使用命名查询有什么好处 [英] What are the advantages of using named queries under Hibernate Annotation

查看:83
本文介绍了在Hibernate注释下使用命名查询有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用命名查询与我们拥有的相比,有什么优势吗?查看性能,可用性,可维护性等.

Are there any advantages of using named queries vs what we have? Looking at performance, usability, maintainability etc etc....

在我们的应用程序中,我们将查询定义如下:

In our application we have defined our queries as such:

private static final String SELECT_CODE_FOR_STORE = "select DISTINCT code from Code code "
        + "join code.codeDescriptions codeDesc "
        + "join codeDesc.stores store where store.id =:"
        + DataAccessConstants.PARAM_STORE_ID;

(这些都放置在DAO对象中,并且它们很多.)

(These are all placed into the DAO object and there are many of them.)

我们通过使用

Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("storeId", codeDescriptionSearchCriteria.getStoreId());
List<Code> list = getJpaTemplate().findByNamedParams(
        SELECT_CODE_FOR_STORE, paramMap);
return list; 

仅此而已:

public List findByNamedParams(final String arg0, 
                              final Map<String, 
                              ? extends Object> arg1) throws DataAccessException 
{
  return org.springframework.orm.jpa.JpaTemplate.findByNamedParams(arg0, arg1);
}

与使用

@NamedQuery(name="SELECT_CODE_FOR_STORE", query="select ......")

DAO对象的顶部.

我看到了此帖子这似乎是组织所有这些查询的好方法.如果我们有很多此类查询,也许是时候重新评估我们的数据库和对象结构了.

I saw this posting which seems to be a good way to organize all these queries. Or maybe it is time to re-evaluate our database and object structures if we have so many of these type of queries.

推荐答案

在您链接到的问题中,我使用第二种方法(使用字符串常量命名查询).使用命名查询的主要优点是Hibernate在启动时会解析查询,因此可以快速检测到任何错误.

I use the second approach in the question you linked to (named queries with string constants ). The main advantage of using named queries is that Hibernate parses the queries at startup so any errors will detected quickly.

对于您的整体方法,如果您非常需要命名查询,我肯定会质疑您的域模型.对于某些应用程序,这是必需的,但也许要考虑用实体中的延迟加载替换联接.还应通过示例和准则来研究使用hobernate查询,因​​为它们也可以减少面向对象的命名查询的使用.

As for your overall approach I would definitely question your domain model if you need named queries a lot. For some applications this is necessary but maybe look at replacing joins with lazy loads in the entities. Also look at using hobernate query by example and criteria as these can also reduce use of named queries in an object orientated way.

这篇关于在Hibernate注释下使用命名查询有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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