Grid生成了太多的hibernate查询 - FetchMode.JOIN不起作用

时间:2013-12-11 16:48:23

标签: java hibernate spring-mvc hql hibernate-mapping

我正在使用Spring MVC和Hibernate开发一个webapp。事实上,我需要展示我所有客户的客户,并且每个客户都有另一个实体关联(“Cobrador”,我不知道这里的英文翻译,对不起),我正在使用JQgrid来实现这样的目标。当我执行网格时,我在日志中看到:

Hibernate: select cliente0_.id as id1_0_, cliente0_.activo as activo2_0_, cliente0_.apellido as apellido3_0_, cliente0_.cobrador as cobrador8_0_, cliente0_.dni as dni4_0_, cliente0_.email as email5_0_, cliente0_.nombre as nombre6_0_, cliente0_.telefono as telefono7_0_ from clientes cliente0_ where cliente0_.activo=1
Hibernate: select cobrador0_.id as id1_1_0_, cobrador0_.activo as activo2_1_0_, cobrador0_.apellido as apellido3_1_0_, cobrador0_.dni as dni4_1_0_, cobrador0_.email as email5_1_0_, cobrador0_.nombre as nombre6_1_0_, cobrador0_.telefono as telefono7_1_0_ from cobradores cobrador0_ where cobrador0_.id=?
Hibernate: select cobrador0_.id as id1_1_0_, cobrador0_.activo as activo2_1_0_, cobrador0_.apellido as apellido3_1_0_, cobrador0_.dni as dni4_1_0_, cobrador0_.email as email5_1_0_, cobrador0_.nombre as nombre6_1_0_, cobrador0_.telefono as telefono7_1_0_ from cobradores cobrador0_ where cobrador0_.id=?
Hibernate: select cobrador0_.id as id1_1_0_, cobrador0_.activo as activo2_1_0_, cobrador0_.apellido as apellido3_1_0_, cobrador0_.dni as dni4_1_0_, cobrador0_.email as email5_1_0_, cobrador0_.nombre as nombre6_1_0_, cobrador0_.telefono as telefono7_1_0_ from cobradores cobrador0_ where cobrador0_.id=?

基本上获取客户端,然后,为每个客户端获取相关的“cobrador”。我的客户端实体配置如下:

@Entity
@Table(name="clientes")
public class Cliente {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;    
private String apellido;
private String nombre;
private int dni;
private String telefono;
private String email;
private boolean activo;
@ManyToOne
@JoinColumn(name="cobrador")
@Fetch(FetchMode.JOIN)
private Cobrador cobrador;

//Contructors, getters and setters
}

BTW:最后的休眠执行是:

@Override
@Transactional
public List<T> getAllFiltering(String filter) { 
    Query q = sessionFactory.getCurrentSession().createQuery("from " + type.getSimpleName() + " " + filter);
    return q.list();
}

其中is和filter是“where activo = true”。

是否有配置此关系以便在加载网格时仅执行1个查询?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我知道这不是很方便,但如果您使用Hibernate查询(使用createQuery方法的I.E),HQL将不会使用获取策略。如果要使其正常工作,则必须使用Criteria API或在HQL查询中指定连接。

在您的情况下,查询可能是这样的:

from Cliente c left join fetch c.cobrador

来自Hibernate documentation

  

映射文档中定义的获取策略会影响:

     
      
  • 通过get()或load()
  • 进行检索   
  • 在导航关联时隐式发生的检索
  •   
  • 条件查询
  •   
  • HQL查询是否使用了子选择提取
  •   

如您所见,定义的提取策略不会影响HQL查询 如果JOIN是fetchMode。