休眠:双向一对多

时间:2013-09-18 08:37:04

标签: hibernate hibernate-mapping

我有以下结构:

@Entity
@Table(name = "requests")
public class Request extends BaseHistory  {
   ...

   @OneToMany(mappedBy = "request", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, orphanRemoval = true)
   private List<RequestService> services = new ArrayList<RequestService>(0);
   ... }

@Entity
@Table(name = "requestservices")
public class RequestService extends BaseCancellation  {
   ...
   @ManyToOne
   @JoinColumn(name = "RequestId")
   private Request request;
   .. }

查询:

Criteria query = session.createCriteria(Request.class)
        .createAlias("services", "services")
        .add(Restrictions.eq("services.cancelled", type == RequestType.Cancelled))
        .add(Restrictions.disjunction()
                .add(Restrictions.eq("services.state", RequestServiceState.New))
                .add(Restrictions.conjunction()
                        .add(Restrictions.eq("services.state", RequestServiceState.InProcess))
                        .add(Restrictions.eq("handler", employeeId)))
                        .add(Restrictions.eq("services.state", RequestServiceState.Pending))
                    )
                .addOrder(Order.asc("services.executionDate"))
                .addOrder(Order.asc("services.executionTime"));

最后我收到以下SQL:

select
        ...
    from
        requests this_ 
    left outer join
        requestservices services1_ 
            on this_.Id=services1_.RequestId 
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    left outer join
        requests request4_ 
            on services1_.RequestId=request4_.Id
    where
       ...
    order by
        ...

是否有正常的行为,是否有一个额外的反向连接再次连接子实体和父实体?

谢谢

1 个答案:

答案 0 :(得分:0)

你没有双向关系,而是两个单向关系。

您必须使用mappedby="..."中的@OneToMany来建立双向关系。

@OneToMany(mappedby="request")
相关问题