我有一个JPA实体对象,其结构如下:
@Table(name="item_info")
class Item(){
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name="item_name")
private String itemName;
@Column(name="product_sku")
private String productSku;
@Column(name="item_json")
private String itemJsonString;
@Transient
private ItemJson itemJson;
//Getters and setters
}
itemJsonString字段包含一个json字符串值,例如'{"key1":"value1","key2":"value2"}'
而itemJson字段包含对应于json字符串的映射对象。
我从数据库中获取此实体对象的方式如下:
Item item = itemRepository.findOne(1L); // Returns item with id 1
现在,itemJson字段为空,因为它是一个瞬态字段。我必须使用Jackson的ObjectMapper手动设置它,如下所示:
itemJson = objectMapper.readValue(item.getItemJsonString(), ItemJson.class);
当我执行itemRepository.findOne()
时,如何使其自动将itemJson字段映射到Item对象并返回该对象?
@Autowired
注解来注入ObjectMapper:@Autowired private ObjectMapper om
,但是没有成功。只有在将mapper定义为静态变量private static ObjectMapper om
并通过autowired setter进行初始化时才能正常工作。您能否解释一下为什么简单的字段自动装配不起作用?我之所以问这个问题,是因为您在每个转换器方法中都使用了ObjectMapper mapper = new ObjectMapper();
而不是使用自动装配。 - chill appreciatorprivate static final ObjectMapper
根据您的用例可能更有效率。 - stdunbarObjectMapper mapper = new ObjectMapper();
就是不起作用。映射器无法转换我需要的内容。但是当我自动装配映射器时,它可以工作。在自动装配的情况下,我担心像registerModule()
和setDateFormat()
这样的操作会导致副作用。因为我使用调试器检查过,自动装配的ObjectMapper
对象始终是相同的对象。你认为修改自动装配的ObjectMapper
对象的状态是不好的吗? - chill appreciator