java巧用@Convert实现表字段自动转entity
作者:螺蛳小公鸡
本文主要介绍了java巧用@Convert实现表字段自动转entity,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1.背景
本人自入职以来,接了一堆历史包(shi)袱(shan),其中有个服务是基于MongoDB实现的,而公司要搞信创化,去掉MongoDB是迟早的事,于是便开始分析底层数据结构,计划用pg替换MongoDB。
2.难点
2.1 数据结构不同
MongoDB是文档型数据库,而pg是关系型数据库,原项目MongoDB的collection中某些字段类型为List或者entity,存在一对多的情况,如果采用新建关联表的方式,会增加数据结构复杂性,且底层数据几乎不会变,因此,觉得直接用VARCHAR类型存储List类型的json串。
2.2 数据类型转换
服务的数据库持久化使用的是jpa,原来MongoDB类型会自动转成List,如下列的options属性
@Data @Document(collection = "input_item") public class InputItem implements Comparable<InputItem> { @Id private String itemCode; private String title; private String description; private int itemType; private List<InputItemOption> options; private String defaultOptionNum; private String unit; private boolean whetherActive; }
转成pg后,options字段在数据库中是String类型,需要转成List。经过调研,可以采用自定义Converter+注解@Convert来实现。
2.2.1 List类型
1)自定义Converter
import com.alibaba.fastjson.JSON; import javax.persistence.AttributeConverter; /** * @ClassName JpaConverterListJson * @Description jpa list转换为String 相互转换工具类 * @Author ygt * @Date 2021/3/3 14:49 * @Version V1.0 */ public class JpaConverterListJson implements AttributeConverter<Object, String> { @Override public String convertToDatabaseColumn(Object o) { return JSON.toJSONString(o); } @Override public Object convertToEntityAttribute(String s) { return JSON.parseArray(s); } }
2)@Convert注解
import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; import lombok.Data; import javax.persistence.*; /** * * @Description 输入项实体类 * */ @ApiModel("") @JsonInclude(value = JsonInclude.Include.NON_NULL) @Table(name = "input_item") @Builder @AllArgsConstructor @NoArgsConstructor @Data @Entity public class InputItem implements Comparable<InputItem> { @GeneratedValue @Column(name = "id") @Id private String itemCode; @Column(name = "title") private String title; @Column(name = "description") private String description; @Column(name = "itemtype") private int itemType; @Convert(converter = JpaConverterListJson.class) private List<InputItemOption> options; @Column(name = "defaultoptionnum") private String defaultOptionNum; @Column(name = "unit") private String unit; @Column(name = "whetheractive") private Boolean whetherActive; @Override public int compareTo(InputItem o) { int index1 = Integer.parseInt(this.itemCode.substring(this.itemCode.lastIndexOf('_') + 1)); int index2 = Integer.parseInt(o.itemCode.substring(o.itemCode.lastIndexOf('_') + 1)); if (index1 < index2) { return -1; } else { return 1; } } }
2.2.2 entity类型
1)自定义Converter
import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.databind.ObjectMapper; import com.test.src.domain.index.interest.InterestCreditScoreSection; import javax.persistence.AttributeConverter; import java.lang.reflect.ParameterizedType; /** * @ClassName JpaConverterListJson * @Description jpa 泛型T转换为String 相互转换工具类 * @Author ygt * @Date 2021/3/3 14:49 * @Version V1.0 */ public class JpaConverterObjectJson<T> implements AttributeConverter<T, String> { private static final ObjectMapper objectMapper = new ObjectMapper(); @Override public String convertToDatabaseColumn(T o) { try { return objectMapper.writeValueAsString(o); } catch (Exception e) { throw new RuntimeException("Failed to convert object to string", e); } } @Override public T convertToEntityAttribute(String s) { try { return objectMapper.readValue(s, (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); } catch (Exception e) { throw new RuntimeException("Failed to convert string to object", e); } } }
import com.test.src.domain.index.interest.InterestCreditScoreSection; public class InterestCreditScoreSectionConverter extends JpaConverterObjectJson<InterestCreditScoreSection>{ }
2)@Convert注解
import com.fasterxml.jackson.annotation.JsonInclude; import com.test.src.utils.InterestCreditScoreSectionConverter; import io.swagger.annotations.ApiModel; import lombok.NoArgsConstructor; import lombok.*; import javax.persistence.*; /** * * @Description 利率授信实体类 */ @ApiModel("") @JsonInclude(value = JsonInclude.Include.NON_NULL) @Table(name = "interest_credit") @Builder @AllArgsConstructor @NoArgsConstructor @Data @Entity public class InterestCredit { @Id @GeneratedValue @Column(name = "id") private String itemNo; @Column(name = "recommendinterestformula") private String recommendInterestFormula; //推荐执行利率计算公式; @Convert(converter = InterestCreditScoreSectionConverter.class) @Column(name = "interestcreditscoresection") private InterestCreditScoreSection interestCreditScoreSection; }
3.总结
针对不好处理的json string类型,可通过自定义converter+@Convert的方式实现自动转换,另外,可在自定义converter类上加@Convert(autoApply = true)实现全局自动转换。
到此这篇关于java巧用@Convert实现表字段自动转entity的文章就介绍到这了,更多相关java 表字段自动转entity内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!