zl程序教程

您现在的位置是:首页 >  其他

当前栏目

基于JPA的属性转换器AttributeConverter

属性 基于 jpa 转换器
2023-06-13 09:13:14 时间

数据库存放的数据类型有限,且使用也不方便,因此需要实现直接从映射的实体类中拿到比如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)

Post Views: 74