如何使spring数据rest引用相同的实体类型?

guz6ccqo  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(365)

我有这个实体:

@Entity
@Data
@NoArgsConstructor
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "employee_id")
    private Long id;

    private String firstName;

    private String lastName;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "manager_id")
    private Employee manager;
}

与相应的存储库:

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // ..
}

当我做一个 GET 请求按查找员工 id 我得到这个结果:

{
   "firstName":"Steven",
   "lastName":"King",
   "_links":{
      "self":{
         "href":"http://localhost:8081/api/employees/100"
      },
      "employee":{
         "href":"http://localhost:8081/api/employees/100"
      },
      "manager":{
         "href":"http://localhost:8081/api/employees/100/manager"
      }
   }
}

这个 http://localhost:8081/api/employees/100/manager 只是不适用于 Lazy 抓取,那么如何将其更改为: http://localhost:8081/api/employees/99 99是什么地方 id 史蒂文的经理?

rur96b6h

rur96b6h1#

根据spring数据rest引用,您可以定义 RepresentationModelProcessor<EntityModel<T>> ,在序列化类型的实体时,由spring data rest自动拾取 T .
你可以建立一个 EntityModel 你自己去吧。

@Component
public class EmployeeModelProcessor implements RepresentationModelProcessor<EntityModel<Employee>> {

    private final RepositoryEntityLinks entityLinks;

    public EmployeeModelProcessor(RepositoryEntityLinks entityLinks) {
        this.entityLinks = entityLinks;
    }

    @Override
    public EntityModel<Employee> process(EntityModel<Employee> employeeModel) {

        Employee employee = employeeModel.getContent();

        EntityModel<Employee> newEmployeeModel = EntityModel.of(employee);
        newEmployeeModel.add(employeeModel.getRequiredLink(IanaLinkRelations.SELF));
        newEmployeeModel.add(employeeModel.getRequiredLink("employee"));

        if (null != employee.getManager()) {
            newEmployeeModel.add(entityLinks.linkToItemResource(Employee.class, employee.getManager().getId()).withRel("manager"));
        }

        return newEmployeeModel;
    }

}

你可以找到关于 RepositoryEntityLinks 在这里。
那么响应json应该变成

{
   "firstName":"Steven",
   "lastName":"King",
   "_links":{
      "self":{
         "href":"http://localhost:8081/api/employees/100"
      },
      "employee":{
         "href":"http://localhost:8081/api/employees/100"
      },
      "manager":{
         "href":"http://localhost:8081/api/employees/99"
      }
   }
}

相关问题