如何使 Spring Data Rest 参考相同的实体类型工作?

How to make Spring Data Rest work with reference to the same entity type?

我有这个实体:

@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> {
    // ..
}

当我通过 id 发出 GET 请求 查找员工时,我得到了这个结果:

{
   "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 where 99是史蒂文经理的id

根据 Spring Data REST Reference,您可以定义类型 RepresentationModelProcessor<EntityModel<T>> 的 bean,在序列化类型 T 的实体时,Spring Data REST 会自动拾取它.

你可以在那里自己建一个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 here.

的文档

那么响应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"
      }
   }
}