在hibernate中使用spring boot配置的jackson objectmapper

eqfvzcg8  于 2021-07-18  发布在  Java
关注(0)|答案(0)|浏览(335)

我想配置hibernate使用jackson的 Objectmapper 由spring创建,用于在json和实体之间Map。在我正在进行的项目中,我已经将jooq配置为使用spring的 ObjectMapper 但是我在如何配置hibernate来使用它时遇到了问题。最终的目标是jooq和hibernate使用相同的方法 ObjectMapper .
我查了弗拉德的这篇文章。不幸的是,文章中给出的所有提示都不适用于我正在进行的项目。
下面是一个我尝试过的配置示例

@Configuration
public class HibernateConfiguration implements HibernatePropertiesCustomizer {
    //Autowire Objectmapper created by Spring
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void customize(Map<String, Object> hibernateProperties) {
        ObjectMapperSupplier objectMapperSupplier = () -> objectMapper;
        // Below config doesn't work since Hibernate types creates it's own mapper
        hibernateProperties.put("hibernate.types.jackson.object.mapper", objectMapperSupplier);
}

还尝试了相同的方法,将objectmapper添加到hibernate-types.properties。


# Used by Hibernate but cannot get reference of Spring managed ObjectMapper since this is class is called outside of Spring's context.

hibernate.types.jackson.object.mapper=path.to.ObjectMapperSupplier

我用了另一种方法,但是失败了 NullpointerException 从json转换为中的实体时 JsonTypeDescriptor 班级。

@Configuration
public class HibernateConfiguration implements HibernatePropertiesCustomizer{

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void customize(Map<String, Object> hibernateProperties) {
        // Underlying implementation needs some JavaType or propertyClass, otherwise when converting 
        // from JSON we get a nullpointer.
        var jsonBinaryType = new JsonBinaryType(objectMapper);
        hibernateProperties.put("hibernate.type_contributors", (TypeContributorList) () -> 
        Collections.singletonList((typeContributions, serviceRegistry) -> 
                      typeContributions.contributeType(jsonBinaryType)));
}

下面是实体超类的类型声明。

// This makes Hibernate types create it's own mapper.
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
@MappedSuperclass
public abstract class Entity{

}

那么,有没有什么可能的解决方案可以让我将spring管理的objectmapper连接到hibernate?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题