如何在spring-boot数据休息时在POST json中传递@EmbeddedId

问题描述 投票:3回答:2

我使用Spring Boot Data REST构建了一个REST API。我正在使用embeddedId并且还实现了BackendIdConverter。

以下是我的Embeddable类

@Embeddable
public class EmployeeIdentity implements Serializable {
    @NotNull
    @Size(max = 20)
    private String employeeId;

    @NotNull
    @Size(max = 20)
    private String companyId;

    public EmployeeIdentity() {}

    public EmployeeIdentity(String employeeId, String companyId) {
        this.employeeId = employeeId;
        this.companyId = companyId;
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        EmployeeIdentity that = (EmployeeIdentity) o;

        if (!employeeId.equals(that.employeeId)) return false;
        return companyId.equals(that.companyId);
    }

    @Override
    public int hashCode() {
        int result = employeeId.hashCode();
        result = 31 * result + companyId.hashCode();
        return result;
    }
}

这是我的员工模型

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

    @EmbeddedId
    private EmployeeIdentity id;

    @NotNull
    @Size(max = 60)
    private String name;

    @NaturalId
    @NotNull
    @Email
    @Size(max = 60)
    private String email;

    @Size(max = 15)
    @Column(name = "phone_number", unique = true)
    private String phoneNumber;

    public Employee() {}

    public Employee(EmployeeIdentity id, String name, String email, String phoneNumber) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public EmployeeIdentity getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

并使用我的嵌入式ID而不是限定的类名来正确生成资源链接

@Component
public class EmployeeIdentityIdConverter implements BackendIdConverter {

    @Override
    public Serializable fromRequestId(String id, Class<?> aClass) {
        String[] parts = id.split("_");
        return new EmployeeIdentity(parts[0], parts[1]);
    }

    @Override
    public String toRequestId(Serializable source, Class<?> aClass) {
        EmployeeIdentity id = (EmployeeIdentity) source;
        return String.format("%s_%s", id.getEmployeeId(), id.getCompanyId());
    }

    @Override
    public boolean supports(Class<?> type) {
        return Employee.class.equals(type);
    }
}

这是我的存储库代码

@RepositoryRestResource(collectionResourceRel = "employees", path = "employees")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, EmployeeIdentity> {
}

这适用于GET请求,但我需要能够POST。当我使用json进行POST时,我注意到的第一件事

{
  "id": {
       "employeeId": "E-267", 
       "companyId": "D-432"
  },
  "name": "Spider Man", 
  "email": "[email protected]", 
  "phoneNumber": "+91-476253455"
}

这不起作用。 EmployeeIdentityIdConverter#fromRequestId抛出空指针异常,因为string参数为null。所以我添加了一个空检查,并在id为null时返回默认的EmployeeIdentity。正如这个答案https://stackoverflow.com/a/41061029/4801462所描述的那样

修改后的EmployeeIdentityIdConverter#fromRequestId

@Override
public Serializable fromRequestId(String id, Class<?> aClass) {
    if (id == null) {
        return new EmployeeIdentity();
    }
    String[] parts = id.split("_");
    return new EmployeeIdentity(parts[0], parts[1]);
}

但这引发了另一个问题。我的hashCode和equals的实现现在通过空指针异常,因为使用了默认构造函数而employeeId和companyId为null。

为了解决这个问题,我给employeeId和companyId提供了默认值

**修改后的Employee#Employee()构造函数*

public Employee() {
    this.employeeId = "";
    this.companyId = "";
}

注意

我甚至不确定我上面做了什么。我只是试图解决发生的小问题。

顺便说一句,如果你猜对了这不起作用,那么你是对的。虽然我没有收到错误并且请求成功,但我没有得到我期望的行为。使用空employeeId和companyId创建了一个新条目。

如何使POST为REST API,其模型使用带有Spring引导数据的@EmbeddedId?

java spring-boot spring-data-rest
2个回答
3
投票

这是另一种解决方案。 (虽然还不完美。)

公开您的Employee类的id:

@Configuration
  protected class MyRepositoryRestConfigurer implements RepositoryRestConfigurer {

   @Override
   public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
     config.exposeIdsFor(ThemeMessage.class);
   }
}

将以下行添加到转换器中(在POST请求期间,id将为null):

@Override
public Serializable fromRequestId(String id, Class<?> aClass) {
    if(id==null) {
      return null;
    }
    String[] parts = id.split("_");
    return new EmployeeIdentity(parts[0], parts[1]);
}

以下POST请求将起作用:

{
  "id": {
       "employeeId": "E-267", 
       "companyId": "D-432"
  },
  "name": "Spider Man", 
  "email": "[email protected]", 
  "phoneNumber": "+91-476253455"
}

但是,id字段将在所有响应中公开。但也许这不是一个真正的问题,因为当你使用复合id时,它通常意味着id不仅是一个抽象的标识符,而且它的部分具有应该出现在实体主体中的有意义的内容。

实际上,我正在考虑将这些行添加到我自己的代码中.... :)


0
投票

我有类似的问题,我找不到通过POST /entities端点创建新实体的解决方案。但是,您也可以通过PUT /entities/{newId}端点创建新实体。转换器适用于这些端点。我还完全否定了POST端点,避免了500个响应:

  @PostMapping(value = "/themeMessages")
  public ResponseEntity<Void> postThemeMessage() {

    return new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED);
  }
© www.soinside.com 2019 - 2024. All rights reserved.