1.问题
list通过jpa直接存入数据库会报错这里需要进行转换
2.代码
1.dto对象
@Entity
@Data
@Accessors(chain = true)
public class GameMatch {/*** 主键*/@Id@GeneratedValue(strategy= GenerationType.IDENTITY)private Integer id;/*** 游戏id*/private Integer gameId;/*** 渠道列表*/@Convert(converter = JpaConverterListJson.class)private List<String> subChannels;/*** 位置列表*/@Convert(converter = JpaConverterListJson.class)private List<Integer> positions;/*** 选品数*/@Transientprivate int count =0;/*** 游戏name*/@Transientprivate String gameName ;
}
2.JpaConverterListJson 转换类
import com.alibaba.fastjson.JSON;
import javax.persistence.AttributeConverter;
/*** @ClassName JpaConverterListJson* @Description jpa list转换为test 相互转换工具类* @Author ygt* @Date 2021/3/3 14:49* @Version V1.0*/
public class JpaConverterListJson implements AttributeConverter<Object, String> {@Overridepublic String convertToDatabaseColumn(Object o) {return JSON.toJSONString(o);}@Overridepublic Object convertToEntityAttribute(String s) {return JSON.parseArray(s);}
}
这样既可在数据库中存入string取出来为list了
3.参考资料
@Convert jpa中用于进行数据库存储类型与程序中类型的转换
SPRING JPA 自动转换LIST为JSON并存储到MYSQL 的STRING