将JPA实体的JSON字符串列自动映射到Java对象

dru*_*ist 6 java json jpa jackson

我有一个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

}
Run Code Online (Sandbox Code Playgroud)

itemJsonString字段包含一个json字符串值,如 '{"key1":"value1","key2":"value2"}'

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

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

Item item = itemRepository.findOne(1L);    // Returns item with id 1
Run Code Online (Sandbox Code Playgroud)

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

itemJson = objectMapper.readValue(item.getItemJsonString(), ItemJson.class);
Run Code Online (Sandbox Code Playgroud)

我怎样才能这样做itemRepository.findOne(),当我这样做时,它返回一个Item对象,itemJson字段自动映射到json String?

std*_*bar 10

你最好的选择是实现一个javax.persistence.Converter.它看起来像:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

我已经将它与WildFly一起使用了,并且除了将它放在我正在部署的war文件中之外没有做任何事情.