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

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

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

  1. @Configuration
  2. public class HibernateConfiguration implements HibernatePropertiesCustomizer {
  3. //Autowire Objectmapper created by Spring
  4. @Autowired
  5. ObjectMapper objectMapper;
  6. @Override
  7. public void customize(Map<String, Object> hibernateProperties) {
  8. ObjectMapperSupplier objectMapperSupplier = () -> objectMapper;
  9. // Below config doesn't work since Hibernate types creates it's own mapper
  10. hibernateProperties.put("hibernate.types.jackson.object.mapper", objectMapperSupplier);
  11. }

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

  1. # Used by Hibernate but cannot get reference of Spring managed ObjectMapper since this is class is called outside of Spring's context.
  2. hibernate.types.jackson.object.mapper=path.to.ObjectMapperSupplier

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

  1. @Configuration
  2. public class HibernateConfiguration implements HibernatePropertiesCustomizer{
  3. @Autowired
  4. ObjectMapper objectMapper;
  5. @Override
  6. public void customize(Map<String, Object> hibernateProperties) {
  7. // Underlying implementation needs some JavaType or propertyClass, otherwise when converting
  8. // from JSON we get a nullpointer.
  9. var jsonBinaryType = new JsonBinaryType(objectMapper);
  10. hibernateProperties.put("hibernate.type_contributors", (TypeContributorList) () ->
  11. Collections.singletonList((typeContributions, serviceRegistry) ->
  12. typeContributions.contributeType(jsonBinaryType)));
  13. }

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

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

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

暂无答案!

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

相关问题