JPA-如何使用来自实体继承的criteriaBuilder.construct填充DTO

时间:2018-10-26 21:07:03

标签: java hibernate spring-boot jpa spring-data-jpa

我有以下(最小和部分)JPA实体:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type")
public abstract class Employee implements Serializable {
    @Id
    protected Long id;
    ...
}

@Entity
...
public class FullTimeEmployee extends Employee implements Serializable {
    private BigDecimal salary;
    ...
}

@Entity
...
public class PartTimeEmployee extends Employee implements Serializable {
   private BigDecimal hourlyWage;
   private BigDecimal maxHoursWeek;
    ...
}

当前,我们正在使用spring-data-jpa进行查询,如下所示:

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findAll();
}

但是,这样一来,我们就会遇到“ N + 1”问题和很多选择,因此,我决定使用Criteria API并将其选择到DTO中,如下所示:

public List<EmployeeDTO> findAll() {

    CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<EmployeeDTO> criteriaQuery = criteriaBuilder.createQuery(EmployeeDTO.class);

    Root<Employee> root = criteriaQuery.from(Employee.class);
    Root<FullTimeEmployee> fullTimeEmployeeRoot = criteriaBuilder.treat(root, FullTimeEmployee.class);
    Root<PartTimeEmployee> partTimeEmployeeRoot = criteriaBuilder.treat(root, PartTimeEmployee.class);

    criteriaQuery.select(criteriaBuilder.construct(EmployeeDTO.class,
                          root.get("id"), root.get("name"), 
                          fullTimeEmployeeRoot.get("salary"), 
                          partTimeEmployeeRoot.get("hourlyWage"))
    );

    return this.entityManager
            .createQuery(criteriaQuery).getResultList();
}

这是我们的(示例)DTO

@Getter
@Setter
@AllArgsConstructor
public class EmployeeDTO {
    private Long id;
    private String name;
    private BigDecimal fullTimeEmployeeSalary;
    private BigDecimal partTimeEmployeeHourlyWage;
    private BigDecimal partTimeEmployeeMaxHoursWeek;
    ...
}

但是,我们得到了0个结果。

我们的休眠输出如下:

SELECT employee.id, employee.name, fullTimeEmployee.salary, partTimeEmployee.hourlyWage partTimeEmployee.maxHoursWeek ... FROM employees employee INNER JOIN fullTimeEmployees fullTimeEmployee on fullTimeEmployee.id = employee.id INNER JOIN partTimeEmployees partTimeEmployee on partTimeEmployee.id = employee.id

我的问题是:最好的方法是什么?我如何将这些内部联接转换为左侧联接?存在更好的方法吗?

谢谢。 :)

1 个答案:

答案 0 :(得分:0)

首先,我要感谢您提出的格式很好的问题-您在制作minimal, complete, and verifiable example方面做得很好。我认为您不想将结果投影到您所描述的此类中。具有salaryhourlyWage值的类意味着您一直一直在检查null,这是一个非常糟糕的设计决策。更好的方法是从employeeRepository获取不同类型的列表,并使用面向对象的原则来处理混合类型。这正是OOP发明的目的。

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type")
public abstract class Employee implements Serializable {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    protected Long id;
    public abstract BigDecimal getPay();

@Entity
public class FullTimeEmployee extends Employee {
    private BigDecimal salary;
    private int daysWorked;
    @Override
    public BigDecimal getPay() {
        return salary
                .multiply(BigDecimal.valueOf(daysWorked))
                .divide(BigDecimal.valueOf(Year.now().length()), RoundingMode.HALF_DOWN);
    }

@Entity
public class PartTimeEmployee extends Employee {
    private BigDecimal hourlyWage;
    private int hoursWorked;
    @Override
    public BigDecimal getPay() {
        return hourlyWage.multiply(BigDecimal.valueOf(hoursWorked));
    }

然后

BigDecimal sum = employeeRepo.findAll()
                     .stream()
                     .map(e->e.getPay())
                     .reduce(BigDecimal.ZERO, BigDecimal::add);