Site Overlay

基于JPA的属性转换器AttributeConverter

数据库存放的数据类型有限,且使用也不方便,因此需要实现直接从映射的实体类中拿到比如JSONObject等格式的数据,反之,存取的时候我们也按照对应的格式进行存取转换。
要实现这个功能需要实现AttributeConverter这个接口

<pre class="wp-block-syntaxhighlighter-code">
import com.miracle.dson.Dson;
import org.springframework.stereotype.Component;

import javax.persistence.AttributeConverter;

/**
 * @Author Diuut
 * @Date 2020/4/24  14:03
 */
//实体属性类型转换器
@Component
public class DsonMapConverter implements AttributeConverter&amp;amp;lt;Dson, String&amp;gt; {
    @Override
    public String convertToDatabaseColumn(Dson attribute) {
        //放到数据库中的处理方式
        return attribute.asString();
    }

    @Override
    public Dson convertToEntityAttribute(String dbData) {
       //从数据库中取出来的处理方式
        return Dson.fromMap(dbData);
    }
}
</pre>

之后就可以按照自定义格式直接使用该实体类字段。

记着在转换的字段上加上 @Convert(converter = DsonMapConverter.class)

发表回复

您的电子邮箱地址不会被公开。

A beliving heart is your magic My heart
欢迎来到Diuut的个人博客,这里是我的一些零零碎碎的知识汇总,希望有能帮到你的内容。 | 蜀ICP备2021011635号-1 | Copyright © 2024 Diuut. All Rights Reserved.