Spring Data REST @Idclass not recognized

人盡茶涼 提交于 2019-11-27 20:51:59

Currently Spring Data REST only supports compound keys that are represented as by a single field. That effectively means only @EmbeddedId is supported. I've filed DATAJPA-770 to fix that.

If you can switch to @EmbeddedId you still need to teach Spring Data REST the way you'd like to represent your complex identifier in the URI and how to transform the path segment back into an instance of your id type. To achieve that, implement a BackendIdConverter and register it as 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);
  }
}

If you can't use @EmbeddedId, you can still use @IdClass. For that, you need the BackendIdConverter as Oliver Gierke answered, but you also need to add a Lookup for your domain type:

@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);
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!