hibernate搞砸了我的疑问

时间:2017-05-30 05:23:46

标签: spring hibernate repository hsqldb

您好我写了以下Criteria-API查询,因为多选而创建了一个损坏的sql-select语句。如果我取消注释多选,则查询按预期工作但事情是我不想拥有所有数据。在我的门户网站对象中存在多个关系,并且在我目前的情况下加载所有关系绝对不是必需的。

方法如下:

  @Override
  public Optional<Portal> loadPortalData(long clientId)
  {
    log.trace("loading data for client with id '{}'", clientId);
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Portal> criteriaQuery = criteriaBuilder.createQuery(Portal.class);
    Root<Portal> root = criteriaQuery.from(Portal.class);
    criteriaQuery.multiselect(root.get(Portal_.codes),
                              root.get(Portal_.certificate))
                 .where(criteriaBuilder.equal(root.get(Portal_.id), clientId));
    try
    {
      return Optional.of(entityManager.createQuery(criteriaQuery).getSingleResult());
    }
    catch (NoResultException noResult)
    {
      return Optional.empty();
    }
  }

,破坏的查询如下所示:

30 Mai 2017 07:12:56,305 [main] TRACE mypackage.repository.PortalDaoImpl (PortalDaoImpl.java:39) - loading data for client with id '1'
Hibernate: 
select
    . as col_0_0_,
    portal0_.certificate as col_1_0_ 
from
    portal portal0_ 
inner join
    Code authorisat1_ 
        on portal0_.id=authorisat1_.client_id 
inner join
    certificate certificat2_ 
        on portal0_.certificate=certificat2_.id 
where
    portal0_.id=1

如果我使用multiselect,为什么hibernate会像这样搞乱我的查询?

修改

@Entity
@Table(name = "portal")
public class Portal
{
   ...
   @Valid
   @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, mappedBy = "client")
   private Set<Code> codes = new HashSet<>();

   @Valid
   @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @JoinColumn(name = "certificate", referencedColumnName = "id")
   private Certificate certificate;
   ...
}

和Code类

@Entity
public class Code
{

  @Id
  @GeneratedValue
  private long id;

  @NotNull
  @Column(nullable = false, unique = true)
  private String code;

  @NotNull
  @ManyToOne(fetch = FetchType.EAGER, targetEntity = Portal.class)
  @JoinColumn(name = "client_id", referencedColumnName = "id", nullable = false)
  private Portal client;

  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  @Column(nullable = false)
  private Date creation_time;

  @Column(nullable = false)
  private int expires_in;
  ...
}

1 个答案:

答案 0 :(得分:1)

您无法选择整个集合(codes)。

假设您希望结果的每一行都由代码和证书组成,那么JPQL查询应该是

select code, portal.certificate from Portal portal 
left join portal.codes as code
where portal.id = :id

这当然会返回与给定门户中的代码一样多的行,而不仅仅是一行。

避免加载门户网站实体的其他列可能是过早的,不必要的优化。它应该更容易做到

em.find(Portal.class, id)

或者,如果要在同一查询中加载代码和证书

select distinct portal from Portal portal 
left join fetch portal.certificate
left join fetch portal.codes
where portal.id = :id

将返回包含门户网站的唯一行,并带有预先获取的代码集。

如果你真的希望你的应用程序很快,你应该默认使关联变得懒惰(特别是到多个关联),并在需要时使用fetch join。