QueryDSL在构建谓词查询时添加交叉连接

时间:2015-08-05 10:21:34

标签: java postgresql spring-mvc jpa querydsl

我想从基于用户的modelA中获取modelB中的数据。但对于我将在modelB中记录的每条记录,并非强制性的。因此,当我使用下面的代码来获取数据时,它会返回0条记录。

BooleanExpression searchCriteria = searchCriteria
          .and(
                   qModelA.modelb.user.id.eq(userId)
              )
          .and ( some other conditions as well);

modelA.findAll(searchCriteria, pageable);

当我调试时发现QueryDsl放了Cross join。任何人都可以告诉我如何解决这个问题,是否有任何方式querydsl添加左连接而不是交叉连接?下面是我的两个模特。

@Entity
public class ModelA implements Serializable {

    private Long id;
    private String label;
    private ModelB modelB;

    @Id
    @SequenceGenerator(name = "modelASeq", sequenceName = "modela_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "modelASeq")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(length = 150, nullable = false)
    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    @OneToOne(mappedBy = "modelA", cascade = CascadeType.REMOVE)
    public ModelB getModelB() {
        return modelB;
    }

    public void setModelB(ModelB modelB) {
        this.modelB = modelB;
    }

}

@Entity
public class ModelB implements Serializable {

    private Long id;
    private User user;
    private ModelA modelA;

    @Id
    @SequenceGenerator(name = "modelBSeq", sequenceName = "modelb_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "modelBSeq")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @NotNull
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false )
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @NotNull
    @OneToOne
    @JoinColumn(name = "modela_id", nullable = false)
    public ModelA getModelA() {
        return modelA;
    }

    public void setModelA(ModelA modelA) {
        this.modelA = modelA;
    }

}

1 个答案:

答案 0 :(得分:0)

如果您需要左连接,则需要使用显式连接:

query.from(modelA)
     .leftJoin(modelA.modelB, modelB)
     ...