本文介绍了将JPA实体的JSON字符串列自动映射到Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的JPA实体对象:

I have a JPA entity object with following structure:

@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"}'

The itemJsonString field contains a json string value such as '{"key1":"value1","key2":"value2"}'

itemJson字段包含对应的对象,该对象映射到json字符串.

And the itemJson field contains the corresponding object which maps to the json string.

我从数据库中获取此实体对象,如下所示:

I get this entity object from database as follows:

Item item = itemRepository.findOne(1L);    // Returns item with id 1

现在,itemJson字段为空,因为它是一个瞬态字段.而且我必须使用Jackson的ObjectMapper手动设置它,如下所示:

Now, the itemJson field is null since it is a transient field. And I have to set it manually using Jackson's ObjectMapper as follows:

itemJson = objectMapper.readValue(item.getItemJsonString(), ItemJson.class);

如何做到这样,当我执行itemRepository.findOne()时,它会返回一个Item对象,该对象的itemJson字段会自动映射到json字符串?

How can I make it such that when I do itemRepository.findOne(), it returns an Item object with the itemJson field mapped to the json String automatically?

推荐答案

您最好的选择是实现javax.persistence.Converter.看起来像这样:

Your best bet would be to implement a javax.persistence.Converter. It would look something like:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<ItemJson, String> {

    @Override
    public String convertToDatabaseColumn(ItemJson entityValue) {
        if( entityValue == null )
            return null;

        ObjectMapper mapper = new ObjectMapper();

        return mapper.writeValueAsString(entityValue);
    }

    @Override
    public ItemJson convertToEntityAttribute(String databaseValue) {
        if( databaseValue == null )
            return null;

        ObjectMapper mapper = new ObjectMapper();

        return mapper.readValue(databaseValue, ItemJson.class);

    }
}

我已经在WildFly中使用了它,除了将其保存在我正在部署的war文件中之外,不需要执行任何操作.

I've used this with WildFly and didn't have to do anything except have it be in the war file I was deploying.

这篇关于将JPA实体的JSON字符串列自动映射到Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 17:39