我们关心的是向外界公开内部ID。因此,我正在考虑使用哈希机制(当前的选择是hashids)来散列我们的ID。
我尝试在实体ID字段上使用@JsonSerializer和@JsonDeserializer映射。但是,这只在正文中包含ID时才生效,并且对URL路径中的ID没有影响。
是否有可能这样做,例如类似ID翻译SPI?
发布于 2018-06-25 07:07:02
我唯一能想到的就是创建一个请求筛选器,它将接受URL中带有编码ID的请求,然后解码ID并重定向到一个具有解码ID的URL。
发布于 2018-06-25 16:31:42
您需要的是使用自定义项资源URI在Spring中“从盒子中”工作:
@Configuration
public class RestConfigurer extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.withEntityLookup().forRepository(ModelRepo.class, model -> HashIdUtil.encode(model.getId()), ModelRepo::findByEncodedId);
super.configureRepositoryRestConfiguration(config);
}
}public interface ModelRepo extends JpaRepository<Model, Long> {
default Model findByEncodedId(String encodedId) {
return getById(HashIdUtil.decode(encodedId));
}
Model getById(Long id);
}public class HashIdUtil {
private static final Hashids HASHIDS = new Hashids("salt", 8);
public static String encode(Long source) {
return HASHIDS.encode(source);
}
public static Long decode(String source) {
return HASHIDS.decode(source)[0];
}
}不幸的是,因为这个错误 (我想),PUT/修补程序实体在Spring 2+中不起作用,不像以前的SB (1.5+)版本那样工作。
见我的演示:sdr-hashids-演示
发布于 2022-11-13 09:47:11
你可以试着用转换器。
@Component
@AllArgsConstructor
public class HashIdConverter implements Converter<String, Long> {
private final HashidsUtil hashidsUtil;
@Override
public Long convert(@NonNull String source) {
return hashidsUtil.decodeId(source);
}
}用我刚才告诉你的方式是有点不安全的,但是如果你足够小心的话,它可以做的很好。
https://stackoverflow.com/questions/51017803
复制相似问题