【发布时间】: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