Spring Data REST @Idclass无法识别

时间:2015-08-04 18:19:26

标签: spring hibernate jpa spring-data spring-data-rest

我有一个名为EmployeeDepartment的实体,如下所示

@IdClass(EmployeeDepartmentPK.class) //EmployeeDepartmentPK is a serializeable object
@Entity
EmployeeDepartment{

@Id
private String employeeID;

@Id
private String departmentCode;
---- Getters, Setters and other props/columns
}

我有一个Spring Data Repository定义如下

@RepositoryRestResource(....)
public interface IEmployeeDepartmentRepository extends PagingAndSortingRepository<EmployeeDepartment, EmployeeDepartmentPK> {

}

此外,我有一个注册转换器从String转换为EmployeeDepartmentPK。

现在,对于一个实体,由ID employeeID =&#34; abc123&#34;和departmentCode =&#34; JBG&#34;,我希望在调用SDR接口时使用的ID是abc123_JBG。 例如,http://localhost/EmployeeDepartment/abc123_JBG应该获取结果,实际上确实如此。

但是,当我尝试使用PUT保存实体时,Spring Data Commons的BasicPersistentEntity类中可用的ID属性值为 用于departmentCode的abc123_JBG。这是错的。我不确定这是否是预期的行为。

请帮忙。

谢谢!

3 个答案:

答案 0 :(得分:13)

目前,Spring Data REST仅支持由单个字段表示的复合键。这实际上意味着仅支持@EmbeddedId。我已提交DATAJPA-770来解决此问题。

如果您可以切换到@EmbeddedId,您仍然需要以您希望在URI中表示复杂标识符的方式教授Spring Data REST,以及如何将路径段转换回您的实例id类型。为实现这一点,请实现BackendIdConverter并将其注册为Spring bean。

@Component
class CustomBackendIdConverter implements BackendIdConverter {

  @Override
  public Serializable fromRequestId(String id, Class<?> entityType) {

    // Make sure you validate the input

    String[] parts = id.split("_");
    return new YourEmbeddedIdType(parts[0], parts[1]);
  }

  @Override
  public String toRequestId(Serializable source, Class<?> entityType) {

    YourIdType id = (YourIdType) source;
    return String.format("%s_%s", …);
  }

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

答案 1 :(得分:4)

如果您无法使用@EmbeddedId,您仍然可以使用@IdClass。为此,当Oliver Gierke回答时,您需要BackendIdConverter,但您还需要为您的域类型添加Lookup:

@Configuration
public class IdClassAllowingConfig extends RepositoryRestConfigurerAdapter {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.withEntityLookup().forRepository(EmployeeDepartmentRepository.class, (EmployeeDepartment ed) -> {
        EmployeeDepartmentPK pk = new EmployeeDepartmentPK();
        pk.setDepartmentId(ed.getDepartmentId());
        pk.setEmployeeId(ed.getEmployeeId());
        return pk;
    }, EmployeeDepartmentRepository::findOne);
}

}

答案 2 :(得分:0)

使用@BasePathAwareController自定义Spring数据REST控制器。

    @BasePathAwareController
    public class CustInfoCustAcctController {

    @Autowired
    CustInfoCustAcctRepository cicaRepo;

    @RequestMapping(value = "/custInfoCustAccts/{id}", method = RequestMethod.GET)
    public @ResponseBody custInfoCustAccts getOne(@PathVariable("id") String id) {
        String[] parts = id.split("_");
        CustInfoCustAcctKey key = new CustInfoCustAcctKey(parts[0],parts[1]);
        return cicaRepo.getOne(key);
    }
}

使用示例uri /api/custInfoCustAccts/89232_70

对我来说很好