首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HashIDs的Spring数据Rest ID转换

使用HashIDs的Spring数据Rest ID转换
EN

Stack Overflow用户
提问于 2018-06-25 06:55:51
回答 3查看 1.4K关注 0票数 0

我们关心的是向外界公开内部ID。因此,我正在考虑使用哈希机制(当前的选择是hashids)来散列我们的ID。

我尝试在实体ID字段上使用@JsonSerializer和@JsonDeserializer映射。但是,这只在正文中包含ID时才生效,并且对URL路径中的ID没有影响。

是否有可能这样做,例如类似ID翻译SPI?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-25 07:07:02

我唯一能想到的就是创建一个请求筛选器,它将接受URL中带有编码ID的请求,然后解码ID并重定向到一个具有解码ID的URL。

票数 0
EN

Stack Overflow用户

发布于 2018-06-25 16:31:42

您需要的是使用自定义项资源URI在Spring中“从盒子中”工作:

代码语言:javascript
复制
@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);
    }
}
代码语言:javascript
复制
public interface ModelRepo extends JpaRepository<Model, Long> {

    default Model findByEncodedId(String encodedId) {
        return getById(HashIdUtil.decode(encodedId));
    }

    Model getById(Long id);
}
代码语言:javascript
复制
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-演示

票数 0
EN

Stack Overflow用户

发布于 2022-11-13 09:47:11

你可以试着用转换器。

代码语言:javascript
复制
@Component
@AllArgsConstructor
public class HashIdConverter implements Converter<String, Long> {

    private final HashidsUtil hashidsUtil;

    @Override
    public Long convert(@NonNull String source) {
        return hashidsUtil.decodeId(source);
    }
}

用我刚才告诉你的方式是有点不安全的,但是如果你足够小心的话,它可以做的很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51017803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档