【问题标题】:How to store JSON file as a JSON datatype in mysql using Hibernate / Spring boot?如何使用 Hibernate/Spring boot 将 JSON 文件作为 JSON 数据类型存储在 mysql 中?
【发布时间】:2020-05-13 11:36:21
【问题描述】:

我尝试了几种将 json 文件存储在数据库中的方法,但最终会为每个条目创建不同的列。

我想将它作为“json”类型存储在单个列中。 有可能吗?

我的 json 文件。

users.json

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
...
]

这是一个 spring-boot 应用程序,我有相关的控制器和服务。

在我的域包中。 (地址和公司是可嵌入的类)

用户.java

@Data
@AllArgsConstructor @NoArgsConstructor
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String username;
    private String email;
    private String phone;
    private String website;

    @Embedded
    private Address address;

    @Embedded
    private Company company;
}

主文件(存储在数据库中)

TypeReference 和 ObjectMapper 来自 Jackson

@SpringBootApplication
public class JsondbApplication {
    public static void main(String[] args) {
        SpringApplication.run(JsondbApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(UserService service) {
        return args -> {
            ObjectMapper mapper = new ObjectMapper();
            TypeReference<List<User>> reference = new TypeReference<List<User>>() {};
            InputStream stream = TypeReference.class.getResourceAsStream("/json/users.json");
            try {
                List<User> users = mapper.readValue(stream, reference);
                service.save(users);
                System.out.println("Saved!");
            } catch (Exception h) {
                System.out.println("Unable to save! " + h.getMessage());
            }
        };
    }

}

在 mysql 中,它为 id, name, username, ... 创建不同的列

我想使用 spring boot 将其存储在 单列 中作为 json 类型。

【问题讨论】:

  • 请用您用来保存到数据库的代码更新您的问题
  • 已更新,请查收。
  • 为什么要存储在单列中?你不想要两列 - id 和 jsonObj 吗?
  • 我只是想知道我们可以将完整的JSON文档存储为JSON类型吗?

标签: java mysql json hibernate spring-boot


【解决方案1】:

您的代码将 json 读入 User 对象列表并保存到数据库中。您需要编写一些自定义逻辑将其保存为 json。有多种方法可以做到这一点。

你可以这样做

1) 在User 类中添加另一个变量,比如private String jsonData

2) 在@PrePersist方法中,编写序列化逻辑

3) 用 @JsonInclude() 标记其他属性 - 包括在 Jackson @Transient 中 - 在单独列中的持久性中忽略。您可能不想将这些注释添加到 id 属性,因为每个 json 对象都将针对数据库中的特定 ID 进行存储。

所以,新属性应该是这样的

@NonNull
@Column(columnDefinition = "JSON") // Only if Database has JSON type else this line can be removed
private String jsonData;

PrePersist:

@PrePersist
public void prePersist() {
    try {
        this.setJsonData(new ObjectMapper().writeValueAsString(this));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

编辑:@PrePersist 方法中,您可能会遇到@Transient 属性为空的问题。在这种情况下,您可以使用 setter 方法。但是每次在保存调用之前更改任何属性时,您都必须调用此设置器。

public void setJsonData(String jsonData) {
    // Method parameter jsonData is simply ignored
    try {
        this.jsonData = new ObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        log.error(e.getMessage());
    }
}

【讨论】:

  • 使用它创建“jsonData”作为“varchar”。我希望将整个文档存储为“json”类型dev.mysql.com/doc/refman/8.0/en/json.html
  • 尝试将@Column(columnDefinition = "JSON") 用于jsonData。此外,我已更新我的答案以使用 @PrePersist,这是一个更清洁的解决方案。
猜你喜欢
  • 2021-10-25
  • 2021-04-21
  • 2019-10-31
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2019-07-10
相关资源
最近更新 更多