You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Java中的HashMap<>存入MySQL数据表列?

如何将Java Entity中的HashMap字段存入MySQL数据库

我有一个包含HashMap<String, Integer>类型字段的Java实体类Product.java,代码如下:

import java.util.HashMap;
import java.util.Objects;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Product {

    @Id
    private int productCode;
    
    private String name;
    private String brand;
    private String description;
    private int price;
    private HashMap<String, Integer> deliverableTo;
}

我尝试用以下两条INSERT语句将数据存入product-browser数据库的product表,但都失败了:

第一条语句:

INSERT INTO `product-browser`.`product` (`product_code`, `brand`, `deliverable_to`, `description`, `name`, `price`) VALUES ('101', 'nVidia', ('Mumbai', '3'), 'Graphics Card', 'RTX 3060', '30000')

第二条语句:

INSERT INTO `product-browser`.`product` (`product_code`, `brand`, `deliverable_to`, `description`, `name`, `price`) VALUES ('101', 'nVidia', {'Mumbai': '3'}, 'Graphics Card', 'RTX 3060', '30000')

数据表中deliverable_to字段为LONGTEXT类型,我不清楚该如何将HashMap值存入MySQL数据表。


解决方案

1. 直接用SQL插入的正确方式

MySQL中需要将HashMap以标准JSON字符串的格式存入deliverable_to字段,修正后的INSERT语句如下:

INSERT INTO `product-browser`.`product` (`product_code`, `brand`, `deliverable_to`, `description`, `name`, `price`) 
VALUES (101, 'nVidia', '{"Mumbai": 3}', 'Graphics Card', 'RTX 3060', 30000);

注意事项:

  • product_code是int类型,不需要加单引号包裹
  • deliverable_to的值必须是合法JSON字符串:用单引号包裹整体,内部键名用双引号,数字值不需要引号
  • 之前的语句失败原因:('Mumbai', '3')是MySQL行构造器语法,{'Mumbai': '3'}是非标准JSON格式,MySQL无法识别

2. 优化Java Entity类,通过JPA自动处理转换

如果用JPA/Spring Data JPA操作数据库,需要给deliverableTo字段添加注解,让框架自动将HashMap与JSON字符串互转:

方式一:自定义转换器

首先创建一个转换器类,实现AttributeConverter:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Converter(autoApply = true)
public class HashMapToJsonConverter implements AttributeConverter<HashMap<String, Integer>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(HashMap<String, Integer> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to convert HashMap to JSON", e);
        }
    }

    @Override
    public HashMap<String, Integer> convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, HashMap.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to convert JSON to HashMap", e);
        }
    }
}

然后修改Product类的字段:

import javax.persistence.Column;
import javax.persistence.Convert;

// ...其他注解和字段

@Column(columnDefinition = "JSON") // 建议将数据库字段类型改为JSON,比LONGTEXT更合适
@Convert(converter = HashMapToJsonConverter.class)
private HashMap<String, Integer> deliverableTo;
方式二:使用Hibernate内置JSON类型(Hibernate 5.2+)

如果项目用Hibernate作为JPA实现,可以直接用@Type注解,无需自定义转换器:

import org.hibernate.annotations.Type;

// ...其他注解和字段

@Column(columnDefinition = "JSON")
@Type(type = "json")
private HashMap<String, Integer> deliverableTo;

需要确保项目中引入了Hibernate的JSON类型依赖(比如hibernate-types-52等)。

配置完成后,直接通过JPA的save()方法保存Product对象即可,框架会自动处理HashMap到JSON字符串的转换。


内容的提问来源于stack exchange,提问作者Innomight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:05:24