1. Convert注解介绍
1.1 基本用途
实现java bean属性或字段与数据库字段的mapping
1.2 参考maven依赖
<dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa- 2.1 -api</artifactId> <version> 1.0 . 2 .Final</version> </dependency> |
1.3 注解定义
@Target ({METHOD, FIELD, TYPE}) @Retention (RUNTIME) public @interface Convert { /** * Specifies the converter to be applied. A value for this * element must be specified if multiple converters would * otherwise apply. */ Class converter() default void . class ; /** * The attributeName must be specified unless the Convert annotation * is on an attribute of basic type or on an element collection of * basic type. In these cases, attributeName must not be * specified. */ String attributeName() default "" ; /** * Used to disable an auto-apply or inherited converter. * If disableConversion is true, the converter element should * not be specified. */ boolean disableConversion() default false ; } |
2. 使用案例
2.1 背景&目标
背景:播单推荐时间段有很多组,对应的数据库决定使用一个json string字段存储。
目标:期望java代码中按照List<TimeDetailInfo>简洁编码,而使用jpa保存/查询时自动映射到数据库中的time_detail_info varchar(500)存储
2.2 convert实现
import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import javax.persistence.AttributeConverter; import java.util.List; /** * 播单推荐有效期时间段字段转换器 */ public class TimeDetailInfosConvert implements AttributeConverter<List<TimeDetailInfo>, String> { /** * jave bean属性/字段映射到数据库字段 * @param attribute * @return */ @Override public String convertToDatabaseColumn(List<TimeDetailInfo> attribute) { if (attribute == null ) return StringUtils.EMPTY; return JSONObject.toJSONString(attribute); } /** * 数据库字段映射到java bean属性/字段 * @param dbData * @return */ @Override public List<TimeDetailInfo> convertToEntityAttribute(String dbData) { if (StringUtils.isBlank(dbData)) return Lists.newArrayList(); return JSONObject.parseArray(dbData, TimeDetailInfo. class ); } } |
2.3 convert使用
import lombok.Data; import javax.persistence.*; import java.util.List; /** * 播单推荐配置 */ @Data @Entity public class PlaylistRecommendConfig extends BasicEntity{ // 推荐有效时间段 @Convert (converter = TimeDetailInfosConvert. class ) @Column (name= "time_detail_info" ,columnDefinition= "varchar(500)" ) private List<TimeDetailInfo> timeDetailInfos; } |