Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data with Mysql JSON type

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

I have two questions:

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) Does spring data repositories are compatible with such mechanism? e.g. (automated code generation for CRUD operations via the repositories interface)?

like image 491
Urbanleg Avatar asked Jul 02 '26 15:07

Urbanleg


1 Answers

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.

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;

and:

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);
  }
}

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.

like image 187
Sergio Figueras Avatar answered Jul 05 '26 03:07

Sergio Figueras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!