1

我的对象图由 Hibernate 实体组成。现在大多数对象都不存在于新数据库中。然而有些人这样做。所以我的对象是这样的:

Class MyObject{ 
  Set<B> bset;
  Set<C> cset; 
}

bset反序列化后需要实例化和持久化的项目。但是,cset新数据库中已经存在项目,因此我不希望创建新实例。告诉杰克逊我知道如何找到这些参考资料的最佳方式是什么?现在我正在考虑使用自定义序列化器/反序列化器cset,它将通过创建具有数据库 ID 的对象来序列化它,然后通过从数据库中拉出适当的对象来反序列化它。

这有点复杂,我希望有一个更简单的解决方案。有什么建议么?

4

1 回答 1

4

弄清楚了。我需要三样东西:

  1. 一个 JsonCreator 获取 entityManager,并返回一个对象的 id

    @JsonCreator
    @IgnoredMethod
    public static UiElement findById(@JacksonInject EntityManager entityManager, @JsonProperty("id") int id) {
        return entityManager.find(UiElement.class, id);
    }
    
  2. 一个 JsonValue getter 返回一个只有 id 的对象

    @JsonValue
    @Transient
    public Map<String,Integer> getJsonObject(){
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        map.put("id", getId());
        return map;
    }
    
  3. 实体管理器需要注入到 ObjectMapper

    //entitymanager for creating any static data based entities
    InjectableValues injects = new InjectableValues.Std().addValue(EntityManager.class, entityManager);
    mapper.setInjectableValues(injects);
    
于 2013-09-12T14:39:13.007 回答