mysql – 为基于oneTomany关系的查询编写queryDSL谓词查询

我正在使用spring-data,QueryDSL和MySQL.

问题的主要目的是知道如何以queryDSL方式进行这样的查询.给出的例子只是一个提供想法的简单例子.

比如说,有两个表Employee和Certificate.两者之间的关系是ONE(员工)到MANY(证书)

以下是表格,

Employee (id, first_name, last_name);
Certificate (id, name, date, fk_emp);

QueryDSL谓词应该是什么

Returning all employees with name contains (in first_name and last_name) and from that result whose certification between date 22-12-2014 to 22-12-2015

我尝试了但是无法获得如何以QueryDSL方式迭代每个员工的每个证书并返回员工列表.

您的回复将受到高度赞赏!

编辑

以下是实体,

@Entity
@Table(name = "EMPLOYEE")
class Employee {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "FIRST_NAME")
  private String firstName;

  @Column(name = "LAST_NAME")
  private String lastName;

  @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
  private List<Certificate> certificates = new ArrayList<>();
}

@Entity
@Table(name = "CERTIFICATE")
class Certificate {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "CERTIFICATE_NAME")
  private String certificateName;

  @Column(name = "DATE")
  private Date date;

  @ManyToOne
  @JoinColumn(name = "REF_EMPLOYEE")
  private Employee employee;
}
最佳答案
最简单的方法是反转它并查询证书,这很简单,然后您可以从返回的证书中获取员工.

QCertificate certificate = QCertificate.certificate;
BooleanExpression a = certificate.date.between(d1, d2);
BooleanExpression b = certificate.employee.forename.eq("name").
      or(certificate.employee.surname.eq("name"));

certificateRepository.findAll(a.and(b));

如果要查询Employees,请尝试以下针对QueryDSL 4.1.3版的内容.

    QEmployee employee = QEmployee.employee;
    QCertificate certificate = QCertificate.certificate;

    BooleanExpression a = employee.forename.eq("name").or(employee.surname.eq("name"));

    BooleanExpression b = employee.certificates.contains(
        JPAExpressions.selectFrom(certificate).
          where(certificate.employee.eq(employee).
           and(certificate.date.between(d1, d2))));

    userRepository.findAll(a.and(b));

转载注明原文:mysql – 为基于oneTomany关系的查询编写queryDSL谓词查询 - 代码日志