具有Mysql JSON类型的Spring数据 [英] Spring Data with Mysql JSON type

查看:305
本文介绍了具有Mysql JSON类型的Spring数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在项目中将Spring数据与JPA一起使用. MySQL服务器版本是5.7.

We are using spring data with JPA in our project. Out MySQL server version is 5.7.

我有两个问题:

1)Spring数据是否与持久化对象兼容,成为MySQL数据库上的新JSON类型?换句话说,我想拥有一个实体,而不是在其表中包含多个列-它将包含一个具有JSON类型的列.

1) Does spring data compatible with persisting objects into the new JSON type on MySQL db? in other words, I would like to have an entity that instead of having multiple columns in its table - it will contain a single column with the JSON type.

2)spring数据存储库是否与这种机制兼容?例如(通过存储库接口为CRUD操作自动生成代码)?

2) Does spring data repositories are compatible with such mechanism? e.g. (automated code generation for CRUD operations via the repositories interface)?

推荐答案

根据

According with Spring Data Docs Appendix D: Repository query return types, the only supported types are: void, primitives, Wrapper types, T, Iterator, Collection, List, Optional, Stream, Future, CompletableFuture, ListenableFuture, Slice, Page, GeoResult, GeoResults, GeoPage.

如您所见,目前尚不支持.我认为,这背后的想法之一不是所有数据库的常识.

As you can see, for now, it's not supported. One of the ideas behind it I think that it's not a common sense of all databases yet.

很明显,您可以将此存储用作Json,并为其创建一个转换器:

Obviously, you can use this storing as Json, and create a converter for it:

  @Column(name = "configuration", nullable = false)
  @Convert(converter = PluginAnalyzerConfigConverter.class)
  private PluginAnalyzerConfig configuration;

和:

public class PluginAnalyzerConfigConverter implements
    AttributeConverter<PluginAnalyzerConfig, String> {

  @Override public String convertToDatabaseColumn(PluginAnalyzerConfig config) {
    Gson parser = new Gson();
    return parser.toJson(config, PluginAnalyzerConfig.class);
  }

  @Override public PluginAnalyzerConfig convertToEntityAttribute(String source) {
    Gson parser = new Gson();
    return parser.fromJson(source, PluginAnalyzerConfig.class);
  }
}

很明显,如果没有这种方法,您将无法像MySQL那样以一种不错的方式使用Json.但是我认为,如果您创建MySQL专用查询来利用它,那是没有问题的.

Obviously that without that approach, you will not make usage of Json in a nice way like MySQL is capable of. But I think that there's no problem if you create MySQL specialized queries to make use of it.

这篇关于具有Mysql JSON类型的Spring数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆